Data Sharing between Fragments and Activity in Android

こ雲淡風輕ζ 提交于 2019-11-27 05:53:57
Alain Beauvois

Many ways :

1) Activity -> Fragment

2) Activity -> Fragment

3) Fragment -> Activity

  • In your Fragment : create un interface with getter and setter methods (callback methods)
  • In your Activity : implement the interface

4) Fragment -> Activity

  • In your Activity : Create public getter and setter or other methods
  • In your Fragment : called public activity getter, setter or other methods using :

    getActivity().getSomething(), getActivity().setSomething(args) or getActivity().someMethod(args)

You can pass data between fragments in two ways,

First, you can do it by using setArguments(...) and getArguments(....)

Second,you can do it using Call back

Also you can use EventBus. It's really simple. https://github.com/greenrobot/EventBus

Definitely don't use static methods like my old answer :)

//In fragment;
String user = MainActivity.getUserName();

Static methods are my old solution, but definitely bad solution. Don't use them like this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!