(Android基础)activity 和 fragment互相传值

来源:互联网 发布:游戏编程模式 中文 pdf 编辑:程序博客网 时间:2024/06/04 20:11

一,activity往fragment传值,大家都知道不能通过fragment的带参数的构造函数来传值,为什么呢,原因如下:

        Avoid non-default constructors in fragments: use a default constructor plusFragment#setArguments(Bundle) instead

        From the Fragment documentation:
        Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other      constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with    setArguments(Bundle) and later retrieved by the Fragment withgetArguments().     

 我就不翻译了哈,英语不太哈,怕翻译错,那么我们就按照官方文档来,通过在setArguments(bundle)来进行传值,具体如下:

通常我们会先给fragment写一个单例模式,

                                                                 public static TestFragment getInstance(String arg1,int arg2){

                                                                                  Bundle bundle = new Bundle();

                                                                                  bundle.putString("String",arg1);

                                                                                  bundle.putInt("int",arg2);

                                                                                  TestFragment fragment = new TestFragment();

                                                                                  fragment.setArguments(bundle);

                                                                                  returen fragment

                                                                }

然后在Fragment的oncreate()方法中直接getArguments()就能得到bundle对象了,通过bundle就能获取到传递过来的参数了。

二,fragment往activity传值,通过接口回调来传值,把fragment和activity联系到一起的方法是onAttach(Activity activity)方法,具体做法如下:

先在fragmen中onattach(Activity activity)方法中得到activity的对象,然后赋值给你自己定义的接口,具体做法如下:

private CallBack callBack;

interface CallBack{

void test(String str);

}

@override

public void onAttach(Activity activity){

callBack = (CallBack)getActivity();

}

然后在你需要传递参数的地方调用callBack.test("haha");到此在fragment中要做的工作就做完了,然后就是在需要获得fragment中的参数的activity中,先实现CallBack接口,然后实现这个接口的方法就ok了,这个时候就能获取到fragment中传过来的参数了。

       

1 0
原创粉丝点击