Fragment Arguments

 

一个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();//不要忘记
        }

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Bundle来传递数据。在Activity中,可以创建一个Bundle对象,将需要传递的数据放入Bundle中,然后通过setArguments()方法将Bundle对象传递给Fragment。在Fragment中,可以通过getArguments()方法获取传递过来的Bundle对象,然后从中取出需要的数据。具体代码如下: 在Activity中传递数据: ``` Bundle bundle = new Bundle(); bundle.putString("key", "value"); MyFragment fragment = new MyFragment(); fragment.setArguments(bundle); ``` 在Fragment中获取数据: ``` Bundle bundle = getArguments(); String value = bundle.getString("key"); ``` ### 回答2: 在Android开发中,我们可以通过使用Activity来向Fragment传递数据。下面是一个简单的示例。 1. 在Activity中,我们可以通过Bundle对象将数据传递给Fragment。可以在Activity的onCreate方法中创建一个Bundle对象,将需要传递的数据存入bundle中,然后通过Fragment的setArguments方法将bundle传递给Fragment。 ```java Bundle bundle = new Bundle(); bundle.putString("key", "value"); MyFragment fragment = new MyFragment(); fragment.setArguments(bundle); ``` 2. 在Fragment中,我们可以通过getArguments方法获取传递过来的数据。在Fragment的onCreate方法中,可以通过getArguments方法获取到传递过来的bundle对象,然后根据key获取对应的数据。 ```java Bundle bundle = getArguments(); if (bundle != null) { String value = bundle.getString("key"); } ``` 这样,我们就可以在Activity中将数据传递给Fragment,并在Fragment中获取到传递过来的数据。 需要注意的是,当我们重新创建Fragment的实例时,需要重新设置Arguments,因为FragmentManager在重新创建Fragment实例时并不会复制Arguments。另外,在Activity与Fragment的通信过程中,我们需要确保Fragment已经attached到Activity中,否则可能会出现NullPointerException。 这就是通过Activity向Fragment传递数据的基本步骤。希望能对你有所帮助! ### 回答3: 在Android开发中,activity是应用程序中的一个重要组件,而fragment是其中一个UI组件。在进行activity与fragment之间的数据传递时,可以通过使用bundle和接口回调来实现。 1. 使用Bundle传递数据给Fragment:在Activity中,可以创建一个Bundle对象,并通过put方法向Bundle中放入需要传递的数据。然后使用Fragment的setArguments方法将Bundle对象传递给Fragment。在Fragment中,通过getArguments方法获取到Bundle对象,并通过get方法获取到传递的数据。 例如,在Activity中传递数据给Fragment的代码如下: ```java Bundle bundle = new Bundle(); bundle.putString("data", "Hello Fragment"); Fragment fragment = new YourFragment(); fragment.setArguments(bundle); ``` 在Fragment中获取传递数据的代码如下: ```java Bundle bundle = getArguments(); String data = bundle.getString("data"); ``` 2. 使用接口回调传递数据给Fragment:首先,在Activity中创建一个接口,在该接口中定义一个传输数据的方法。然后,在Activity中实现该接口,并将实现的接口对象传递给Fragment。在Fragment中通过接口对象调用接口中的方法,从而实现数据的传递。 例如,先定义一个传递数据的接口: ```java public interface DataCallback { void onDataReceived(String data); } ``` 在Activity中实现该接口并传递给Fragment: ```java public class MainActivity extends AppCompatActivity implements DataCallback { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Fragment fragment = new YourFragment(); ((YourFragment) fragment).setDataCallback(this); } @Override public void onDataReceived(String data) { // 在这里处理接收到的数据 } } ``` 在Fragment中调用接口中的方法传递数据: ```java public class YourFragment extends Fragment { private DataCallback dataCallback; public void setDataCallback(DataCallback dataCallback) { this.dataCallback = dataCallback; } // 在需要的地方调用dataCallback.onDataReceived("Hello Activity"); } ``` 通过以上的方式,就可以实现Activity向Fragment传递数据的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值