Android ApiDemos之FragmentArguments

来源:互联网 发布:嘉实优化红利混合好吗 编辑:程序博客网 时间:2024/04/29 23:23
这个示例展示了如何configure 一个Fragment, 其中展示了2种方法:
1. setArguments()方法
首先 在new 一个Fragment的同时设置Argument, 之后在这个Fragment类的onCreate中取出Argument,在onCreateView中对Argument进行设置。

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


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();//不要忘记
        }
0 1
原创粉丝点击