Android实现Fragment与Activity之间的数据交互

1概念

1 为什么

因为Fragment和Activity一样是具有生命周期,不是一般的bean通过构造函数传值,会造成异常。

2 参考链接

Activity和Fragment传递数据的两种方式

【Fragment精深系列4】Fragment与Activity之间的数据交互

2 Activity把值传递给Fragment

2.1 第一种方式,也是最常用的方式,就是使用Bundle来传递参数

(1)宿主Activity/FragmentAdapter中:

Bundle bundle = new Bundle();
bundle.putString(Constant.INTENT_ID, productId);
Fragment fragment = null;
switch (position) {
     case 0:
        fragment = new ProductImageDetailFragment();
        break;

     case 1:
        fragment = new ProductParamFragment();
        break;

     case 2:
        fragment = new ProductCommentFragment();
        break;

     default:
        break;
}
fragment.setArguments(bundle);
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

(2)Activity/FragmentAdapter中:

Fragment中的onCreatView/onStart()方法中,通过getArgments()方法,获取到bundle对象,然后通过getString的key值拿到我们传递过来的值。

    @Override
    public void onStart() {
        super.onStart();
        if (isAdded()) {//判断Fragment已经依附Activity
            productId = getArguments().getString(Constant.INTENT_ID);
        }
    }
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2.2 第二种方式,是在宿主Activity中定义方法,将要传递的值传递到Fragment中,在Fragment中的onAttach方法中,获取到这个值。

(1)宿主activity中的getTitles()方法

public String getTitles(){
    return "hello";
}
    
    
  • 1
  • 2
  • 3

(2)Fragment中的onAttach方法

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    titles = ((MainActivity) activity).getTitles();//通过强转成宿主activity,就可以获取到传递过来的数据
}
    
    
  • 1
  • 2
  • 3
  • 4
  • 5

2.3 第三种方式,是扩展一下创建Fragment和传递数值

(1)在宿主activity中,创建Fragment

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out);
fragment1 = MyFragment.newInstance("这是第一个fragment");//这里只需要直接调用这个方法,就创建了一个fragment
fragment2 = MyFragment.newInstance("这是第二个fragment");

    
    
  • 1
  • 2
  • 3
  • 4
  • 5

(2)Fragment中

//定义newInstance()实例
static MyFragment newInstance(String s){
        MyFragment myFragment = new MyFragment();
        Bundle bundle = new Bundle();
        bundle.putString("DATA",s);
        myFragment.setArguments(bundle);
        return myFragment;
    }

//同样,在onCreatView中直接获取这个值
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //......
        Bundle bundle = getArguments();
        String data = bundle.getString("DATA");

    }
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3 Fragment把值传递给Activity

3.1 步骤

(1)在fragment中定义一个内部回调接口,再让包含该fragment的activity实现该回调接口,这样fragment即可调用该回调方法将数据传给activity。其实接口回调的原理都一样,以前的博客有讲到,接口回调是java不同对象之间数据交互的通用方法。

(2)activity实现完了接口怎么传给刚才的fragment呢?当fragment添加到activity中时,会调用fragment的方法onAttach(),这个方法中适合检查activity是否实现了OnArticleSelectedListener接口,检查方法就是对传入的activity的实例进行类型转换,然后赋值给我们在fragment中定义的接口。

(3)在一个fragment从activity中剥离的时候,就会调用onDetach方法,这个时候要把传递进来的activity对象释放掉,不然会影响activity的销毁,产生不必要的错误。注意看onAttach方法中的代码,在赋值之前要做一个判断,看看Activity中有没有实现了这个接口,用到了instanceof。如果没有实现接口,我们就抛出异常。

3.2 例子

(1)在宿主activity中,创建Fragment

public class MainActivity extends Activity implements MenuFragment.FragmentInteraction{

    private TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.content_text);
    }

    // 3.2 +实现接口,实现回调
    @Override
    public void process(String str) {
        if (str != null) {
            textView.setText(str);
        }
    }
}
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

(2)Fragment中

public class MenuFragment extends Fragment implements View.OnClickListener {

    // 2.1 定义用来与外部activity交互,获取到宿主activity
    private FragmentInteraction listterner;

    // 1 定义了所有activity必须实现的接口方法
    public interface FragmentInteraction {
        void process(String str);
    }

    // 当FRagmen被加载到activity的时候会被回调
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if(activity instanceof FragmentInteraction) {
            listterner = (FragmentInteraction)activity; // 2.2 获取到宿主activity并赋值
        } else{
            throw new IllegalArgumentException("activity must implements FragmentInteraction");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_menu, container, false);
        View btn = view.findViewById(R.id.tv_button);
        View btn_m = view.findViewById(R.id.movie_button);
        if (btn != null||btn_m!=null) {
            btn.setOnClickListener(this);
            btn_m.setOnClickListener(this);
        }
        return view;
    }

    @Override
    public void onClick(View v) {
        int id  = v.getId();
        switch (id) {
            case R.id.tv_button:
                listterner.process("我是电视剧"); // 3.1 执行回调
                break;
            case R.id.movie_button:
                listterner.process("我是电影");
                break;
        }
    }

    //把传递进来的activity对象释放掉
    @Override
    public void onDetach() {
        super.onDetach();
        listterner = null;
    }
}
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

4 Fragment与Fragment之间的传值

在Activity中加载Fragment的时候、有时候要使用多个Fragment切换、并传值到另外一个Fragment、也就是说两个Fragment之间进行参数的传递,有两个方法。

4.1 通过共同的Activity传递(主要方法)

在Activity里面添加一个字段、来临时保存要一些值。在Activity中定义一个字段、然后添加set和get方法。

(1)在宿主activity中

public class DemoActivity {

    private String mTitle;

    public String getmTitle() {
        return mTitle;
    }

    public void setmTitle(String title) {
        this.mTitle = title;
    }

}
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

(2)Fragment中

// 调用方法、需要注意的是在设值的时候要进行强转一下
((DemoActivity)getActivity()).getmTitle();
    
    
  • 1
  • 2

4.1 通过Bundle来传递(本质还是Activity–>Fragment)

(1)在宿主activity中

ft.hide(getActivity().getSupportFragmentManager().findFragmentByTag(""));
    DemoFragment demoFragment = new DemoFragment();  
    Bundle bundle = new Bundle();  
    bundle.putString("key", "这是方法二");  
    demoFragment.setArguments(bundle);  
    ft.add(R.id.fragmentRoot, demoFragment, SEARCHPROJECT);  
    ft.commit();  
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

(2)Fragment中

String string = getArguments().getString("key");  
    
    
  • 1

1概念

1 为什么

因为Fragment和Activity一样是具有生命周期,不是一般的bean通过构造函数传值,会造成异常。

2 参考链接

Activity和Fragment传递数据的两种方式

【Fragment精深系列4】Fragment与Activity之间的数据交互

2 Activity把值传递给Fragment

2.1 第一种方式,也是最常用的方式,就是使用Bundle来传递参数

(1)宿主Activity/FragmentAdapter中:

Bundle bundle = new Bundle();
bundle.putString(Constant.INTENT_ID, productId);
Fragment fragment = null;
switch (position) {
     case 0:
        fragment = new ProductImageDetailFragment();
        break;

     case 1:
        fragment = new ProductParamFragment();
        break;

     case 2:
        fragment = new ProductCommentFragment();
        break;

     default:
        break;
}
fragment.setArguments(bundle);
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

(2)Activity/FragmentAdapter中:

Fragment中的onCreatView/onStart()方法中,通过getArgments()方法,获取到bundle对象,然后通过getString的key值拿到我们传递过来的值。

    @Override
    public void onStart() {
        super.onStart();
        if (isAdded()) {//判断Fragment已经依附Activity
            productId = getArguments().getString(Constant.INTENT_ID);
        }
    }
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2.2 第二种方式,是在宿主Activity中定义方法,将要传递的值传递到Fragment中,在Fragment中的onAttach方法中,获取到这个值。

(1)宿主activity中的getTitles()方法

public String getTitles(){
    return "hello";
}
  
  
  • 1
  • 2
  • 3

(2)Fragment中的onAttach方法

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    titles = ((MainActivity) activity).getTitles();//通过强转成宿主activity,就可以获取到传递过来的数据
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5

2.3 第三种方式,是扩展一下创建Fragment和传递数值

(1)在宿主activity中,创建Fragment

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out);
fragment1 = MyFragment.newInstance("这是第一个fragment");//这里只需要直接调用这个方法,就创建了一个fragment
fragment2 = MyFragment.newInstance("这是第二个fragment");

  
  
  • 1
  • 2
  • 3
  • 4
  • 5

(2)Fragment中

//定义newInstance()实例
static MyFragment newInstance(String s){
        MyFragment myFragment = new MyFragment();
        Bundle bundle = new Bundle();
        bundle.putString("DATA",s);
        myFragment.setArguments(bundle);
        return myFragment;
    }

//同样,在onCreatView中直接获取这个值
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //......
        Bundle bundle = getArguments();
        String data = bundle.getString("DATA");

    }
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3 Fragment把值传递给Activity

3.1 步骤

(1)在fragment中定义一个内部回调接口,再让包含该fragment的activity实现该回调接口,这样fragment即可调用该回调方法将数据传给activity。其实接口回调的原理都一样,以前的博客有讲到,接口回调是java不同对象之间数据交互的通用方法。

(2)activity实现完了接口怎么传给刚才的fragment呢?当fragment添加到activity中时,会调用fragment的方法onAttach(),这个方法中适合检查activity是否实现了OnArticleSelectedListener接口,检查方法就是对传入的activity的实例进行类型转换,然后赋值给我们在fragment中定义的接口。

(3)在一个fragment从activity中剥离的时候,就会调用onDetach方法,这个时候要把传递进来的activity对象释放掉,不然会影响activity的销毁,产生不必要的错误。注意看onAttach方法中的代码,在赋值之前要做一个判断,看看Activity中有没有实现了这个接口,用到了instanceof。如果没有实现接口,我们就抛出异常。

3.2 例子

(1)在宿主activity中,创建Fragment

public class MainActivity extends Activity implements MenuFragment.FragmentInteraction{

    private TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView) findViewById(R.id.content_text);
    }

    // 3.2 +实现接口,实现回调
    @Override
    public void process(String str) {
        if (str != null) {
            textView.setText(str);
        }
    }
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

(2)Fragment中

public class MenuFragment extends Fragment implements View.OnClickListener {

    // 2.1 定义用来与外部activity交互,获取到宿主activity
    private FragmentInteraction listterner;

    // 1 定义了所有activity必须实现的接口方法
    public interface FragmentInteraction {
        void process(String str);
    }

    // 当FRagmen被加载到activity的时候会被回调
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        if(activity instanceof FragmentInteraction) {
            listterner = (FragmentInteraction)activity; // 2.2 获取到宿主activity并赋值
        } else{
            throw new IllegalArgumentException("activity must implements FragmentInteraction");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_menu, container, false);
        View btn = view.findViewById(R.id.tv_button);
        View btn_m = view.findViewById(R.id.movie_button);
        if (btn != null||btn_m!=null) {
            btn.setOnClickListener(this);
            btn_m.setOnClickListener(this);
        }
        return view;
    }

    @Override
    public void onClick(View v) {
        int id  = v.getId();
        switch (id) {
            case R.id.tv_button:
                listterner.process("我是电视剧"); // 3.1 执行回调
                break;
            case R.id.movie_button:
                listterner.process("我是电影");
                break;
        }
    }

    //把传递进来的activity对象释放掉
    @Override
    public void onDetach() {
        super.onDetach();
        listterner = null;
    }
}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

4 Fragment与Fragment之间的传值

在Activity中加载Fragment的时候、有时候要使用多个Fragment切换、并传值到另外一个Fragment、也就是说两个Fragment之间进行参数的传递,有两个方法。

4.1 通过共同的Activity传递(主要方法)

在Activity里面添加一个字段、来临时保存要一些值。在Activity中定义一个字段、然后添加set和get方法。

(1)在宿主activity中

public class DemoActivity {

    private String mTitle;

    public String getmTitle() {
        return mTitle;
    }

    public void setmTitle(String title) {
        this.mTitle = title;
    }

}
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

(2)Fragment中

// 调用方法、需要注意的是在设值的时候要进行强转一下
((DemoActivity)getActivity()).getmTitle();
  
  
  • 1
  • 2

4.1 通过Bundle来传递(本质还是Activity–>Fragment)

(1)在宿主activity中

ft.hide(getActivity().getSupportFragmentManager().findFragmentByTag(""));
    DemoFragment demoFragment = new DemoFragment();  
    Bundle bundle = new Bundle();  
    bundle.putString("key", "这是方法二");  
    demoFragment.setArguments(bundle);  
    ft.add(R.id.fragmentRoot, demoFragment, SEARCHPROJECT);  
    ft.commit();  
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

(2)Fragment中

String string = getArguments().getString("key");  
  
  
  • 1

猜你喜欢

转载自blog.csdn.net/xingchenhy/article/details/81457300