一个Fragment可以通过两种方式进行配置,一个是Bundle类型参数,一个是layout中的属性。请看下面的例子:

1.主activity的布局文件

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:padding="4dip"    android:gravity="center_horizontal"    android:layout_width="match_parent" android:layout_height="match_parent">    <TextView            android:id="@+id/text"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="0"            android:padding="4dip"            android:layout_gravity="center_vertical|center_horizontal"            android:gravity="top|center_horizontal"            android:textAppearance="?android:attr/textAppearanceMedium"            android:text="@string/fragment_arguments_msg" />    <LinearLayout android:orientation="horizontal" android:padding="4dip"        android:layout_width="match_parent" android:layout_height="wrap_content">        <fragment class="com.example.android.apis.app.FragmentArguments$MyFragment"                android:id="@+id/embedded"                android:layout_width="0px" android:layout_height="wrap_content"                android:layout_weight="1"                android:label="From Layout" />        <FrameLayout                android:id="@+id/created"                android:layout_width="0px"                android:layout_height="wrap_content"                android:layout_weight="1" />    </LinearLayout></LinearLayout>

2.主Activity:

** * Demonstrates a fragment that can be configured through both Bundle arguments * and layout attributes. */public class FragmentArguments extends Activity {    @Override protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.fragment_arguments);        if (savedInstanceState == null) {            // First-time init; create fragment to embed in activity.            FragmentTransaction ft = getFragmentManager().beginTransaction();            Fragment newFragment = MyFragment.newInstance("From Arguments");            ft.add(R.id.created, newFragment);            ft.commit();        }    }    public static class MyFragment extends Fragment {        CharSequence mLabel;        /**         * Create a new instance of MyFragment that will be initialized         * with the given arguments.         */        static MyFragment newInstance(CharSequence label) {            MyFragment f = new MyFragment();            Bundle b = new Bundle();            b.putCharSequence("label", label);            f.setArguments(b);            return f;        }        /**         * Parse attributes during inflation from a view hierarchy into the         * arguments we handle.         */        @Override public void onInflate(Activity activity, AttributeSet attrs,                Bundle savedInstanceState) {            super.onInflate(activity, attrs, savedInstanceState);            TypedArray a = activity.obtainStyledAttributes(R.styleable.FragmentArguments);            mLabel = a.getText(R.styleable.FragmentArguments_android_label);            a.recycle();//不能忘记        }        /**         * During creation, if arguments have been supplied to the fragment         * then parse those out.         */        @Override public void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            Bundle args = getArguments();            if (args != null) {                mLabel = args.getCharSequence("label", mLabel);            }        }        /**         * Create the view for this fragment, using the arguments given to it.         */        @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,                Bundle savedInstanceState) {            View v = inflater.inflate(R.layout.hello_world, container, false);            View tv = v.findViewById(R.id.text);            ((TextView)tv).setText(mLabel != null ? mLabel : "(no label)");                       return v;        }    }}

3.MyFragment中的布局文件hello_world.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text"    android:layout_width="match_parent" android:layout_height="match_parent"    android:gravity="center_vertical|center_horizontal"    android:textAppearance="?android:attr/textAppearanceMedium"    android:text="hello_world"/>
4.资源文件attr.xml
<?xml version="1.0" encoding="utf-8"?> <resources>    <!-- These are the attributes that we want to retrieve for         app/FragmentArguments.java -->    <declare-styleable name="FragmentArguments">        <attr name="android:label" />    </declare-styleable></resources>

总结:

这个示例展示了如何configure 一个Fragment, 其中展示了2种方法:
1. setArguments()方法

这里要记住Fragment的Life cycle: onAttach --- onCreate --- onCreateView --- onActivityCreated.

首先, 在new 一个Fragment的同时设置Argument; 然后,在这个Fragment类的onCreate中取出Argument,在onCreateView中对Argument进行设置。

2. 在view hierarchy的 inflation过程中解析出相关的attributes

以下是Fragment类说明中的一段话:

The attributes of the <fragment> tag are used to control the LayoutParams provided when attaching the fragment's view to the parent container. They can also be parsed by the fragment in onInflate(Activity, AttributeSet, Bundle) as parameters.


本例中定义了一个新的属性:android:label.
定义新属性的方法--- 在res/values/attr.xml中添加

<declare-styleable name="FragmentArguments">
<attr name="android:label" />
</declare-styleable>

之后在layout xml文件中使用这个属性,

<fragment class="com.example.android.apis.app.FragmentArguments$MyFragment" android:id="@+id/embedded" android:layout_width="0px" android:layout_height="wrap_content" android:layout_weight="1" android:label="@string/fragment_arguments_embedded" />


这样就可以在onInflate()方法中把属性值取出来,在onCreateView中进行处理了。

/**
* Parse attributes during inflation from a view hierarchy into the * arguments we handle. */ @Override public void onInflate ( Activity activity , AttributeSet attrs , Bundle savedInstanceState ) { super . onInflate ( activity , attrs , savedInstanceState ); TypedArray a = activity . obtainStyledAttributes ( attrs , R . styleable . FragmentArguments ); mLabel = a . getText ( R . styleable . FragmentArguments_android_label ); a.recycle();//不要忘记 }

更多相关文章

  1. 一款常用的 Squid 日志分析工具
  2. GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
  3. RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
  4. Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
  5. Android模拟翻书效果
  6. Android屏幕区域划分及尺寸获取
  7. android 实现短视频拍摄
  8. android ResolveInfo运用
  9. 如何运行 .smali 程序

随机推荐

  1. ubuntu 10.10下面编译android 4.0 出错
  2. 如何使用APK扩展文件
  3. Android定制--------自定义关机时间
  4. Android(安卓)读取doc文件
  5. FregServer进程,启动Binder线程池,睡眠等待
  6. Android(安卓)8.0 Caused by: java.lang.
  7. android 之绘图
  8. 2011.09.26——— android sample之Notep
  9. 2011.08.26——— android ListView之多
  10. android默认壁纸被拉伸修改