developer.android.com学习笔记Fragment篇(二)

来源:互联网 发布:淘宝联盟怎么贷款 编辑:程序博客网 时间:2024/05/16 18:32

developer.android.com学习笔记Fragment篇(二)

Fragmentandroid3.0中新引用的概念,也就是说在3.0以下的android版本中,不会兼容Fragment。而且在新版本的android中,己经取消了TabActivity,开发文档建议用Fragment代替。

 

Fragment 表现 Activity 中用UI的一个行为或者一部分可以组合多个fragment放在一个单独的activity中来创建一个多界面区域的UI,并可以在多个activity里重用某一个fragment.fragment 想象成一个activity的模块化区域有它自己的生命周期接收属于它的输入事件并且可以在activity运行期间添加和删除. 

例如一个新闻应用可以在屏幕左侧使用一个fragment来展示一个文章的列表然后在屏幕右侧使用另一个fragment来展示一篇文章 – 2fragment并排显示在相同的一个activity并且每一个fragment拥有它自己的一套生命周期回调方法,并且处理它们自己的用户输入事件因此取代使用一个activity来选择一篇文章,而另一个activity来阅读文章 的方式用户可以在相同的activity中选择一篇文章并且阅读

 fragment在你的应用中应当是一个模块化和可重用的组件,因为fragment定义了它自己的布局以及通过使用它自己的生命周期回调方法定义了它自己的行为你可以将fragment包含到多个activity这点特别重要因为这允许你将你的用户体验适配到不同的屏幕尺寸.举个例子你可能会仅当在屏幕尺寸足够大时,在一个activity中包含多个fragment, 并且,当不属于这种情况时,会启动另一个单独的,使用不同fragmentactivity. 

具体的Franment英文文档请到详细阅读:http://developer.android.com/guide/components/fragments.html 

中文文档在百度文库里有篇还不错的翻译:http://wenku.baidu.com/view/d3d341d133d4b14e8524685b.html 

在这里主要分析几个Fragmentdemo

上面这个示例是按照http://developer.android.com/guide/components/fragments.html 这上面的说明完成的。API建议,这类的使用最好用在横屏的机器上,建议把这个fragment_layout.xml 放到res/layout-land/fragment_layout.xml里。然后竖屏的时候建议只放左边这部分,右边这部分可以新建一个Activity来显示。

res/layout-land/fragment_layout.xml内容是:

    android:orientation="horizontal"    android:layout_width="match_parent" android:layout_height="match_parent">    <fragment class="com.example.fragment.FragmentActivity$TitlesFragment"            android:id="@+id/titles" android:layout_weight="1"            android:layout_width="0px" android:layout_height="match_parent" />    <FrameLayout android:id="@+id/details" android:layout_weight="1"            android:layout_width="0px" android:layout_height="match_parent"         android:background="?android:attr/detailsElementBackground" />

主要代码如下:

package com.example.fragment;import android.os.Bundle;import android.app.Activity;import android.app.Fragment;import android.app.FragmentTransaction;import android.app.ListFragment;import android.content.Intent;import android.util.TypedValue;import android.view.LayoutInflater;import android.view.Menu;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.ScrollView;import android.widget.TextView;public class FragmentActivity extends Activity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.fragment_layout);    }          public static class TitlesFragment extends ListFragment {        boolean mDualPane;        int mCurCheckPosition = 0;        @Override        public void onActivityCreated(Bundle savedInstanceState) {            super.onActivityCreated(savedInstanceState);            // Populate list with our static array of titles.            setListAdapter(new ArrayAdapter<String>(getActivity(),                    android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));            // Check to see if we have a frame in which to embed the details            // fragment directly in the containing UI.            View detailsFrame = getActivity().findViewById(R.id.details);            mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;            if (savedInstanceState != null) {                // Restore last state for checked position.                mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
            }            if (mDualPane) {                // In dual-pane mode, the list view highlights the selected item.                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);                // Make sure our UI is in the correct state.                showDetails(mCurCheckPosition);            }        }        @Override        public void onSaveInstanceState(Bundle outState) {            super.onSaveInstanceState(outState);            outState.putInt("curChoice", mCurCheckPosition);        }        @Override        public void onListItemClick(ListView l, View v, int position, long id) {            showDetails(position);        }        /**         * Helper function to show the details of a selected item, either by         * displaying a fragment in-place in the current UI, or starting a         * whole new activity in which it is displayed.         */        void showDetails(int index) {            mCurCheckPosition = index;            if (mDualPane) {                // We can display everything in-place with fragments, so update                // the list to highlight the selected item and show the data.                getListView().setItemChecked(index, true);                // Check what fragment is currently shown, replace if needed.                DetailsFragment details = (DetailsFragment)                        getFragmentManager().findFragmentById(R.id.details);                if (details == null || details.getShownIndex() != index) {                    // Make new fragment to show this selection.                    details = DetailsFragment.newInstance(index);                    // Execute a transaction, replacing any existing fragment                    // with this one inside the frame.                    FragmentTransaction ft = getFragmentManager().beginTransaction();                    ft.replace(R.id.details, details);                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);                    ft.commit();                }            } else {                // Otherwise we need to launch a new activity to display                // the dialog fragment with selected text.                Intent intent = new Intent();                intent.setClass(getActivity(), DetailsActivity.class);                intent.putExtra("index", index);                startActivity(intent);            }        }    }            public static class DetailsFragment extends Fragment {        /**         * Create a new instance of DetailsFragment, initialized to         * show the text at 'index'.         */        public static DetailsFragment newInstance(int index) {            DetailsFragment f = new DetailsFragment();            // Supply index input as an argument.            Bundle args = new Bundle();            args.putInt("index", index);            f.setArguments(args);            return f;        }        public int getShownIndex() {            return getArguments().getInt("index", 0);        }        @Override        public View onCreateView(LayoutInflater inflater, ViewGroup container,                Bundle savedInstanceState) {            if (container == null) {                // We have different layouts, and in one of them this                // fragment's containing frame doesn't exist.  The fragment                // may still be created from its saved state, but there is                // no reason to try to create its view hierarchy because it                // won't be displayed.  Note this is not needed -- we could                // just run the code below, where we would create and return                // the view hierarchy; it would just never be used.                return null;            }            ScrollView scroller = new ScrollView(getActivity());            TextView text = new TextView(getActivity());            int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,                    4, getActivity().getResources().getDisplayMetrics());            text.setPadding(padding, padding, padding, padding);            scroller.addView(text);            text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
            return scroller;        }    }}


此程序的源程序下载地址如下:

http://download.csdn.net/detail/wuxia2001/4547087 

利用这个资源,我们还可以做成如下界面:

 

此资源下载地址:

http://download.csdn.net/detail/wuxia2001/4547099 

同样的

 

这么一个界面也可以做出来了,这个界面可以用tabhosttabactivity做,也可用fragment做,在这位朋友的博客上有详细做法:http://blog.csdn.net/edisonkun/article/details/7853373 并有源码下载。

源码下载:(tabhost 和tabcativity)http://download.csdn.net/detail/wuxia2001/4547127

源码下载:(fragment)http://download.csdn.net/detail/wuxia2001/4547131

原创粉丝点击