Data Sharing between Fragments and Activity in Android

后端 未结 3 487

Ive asked a similar question before and didn\'t get an answer and seems many other ppl are searching for an answer. So I am posting this question to hopefully get a clear an

相关标签:
3条回答
  • 2020-11-30 17:35

    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

    0 讨论(0)
  • 2020-11-30 17:38

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

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

    0 讨论(0)
  • 2020-11-30 17:47

    Many ways :

    1) Activity -> Fragment

    • In your Activity : create a bundle and use fragment.setArguments(bundle)
    • in your Fragment : use Bundle bundle = getArguments()

    2) Activity -> Fragment

    • In your Fragment : create a public method

    • In your Activity : call an active fragment public method :

      getSupportFragmentManager().findFragmentById(R.id.your_fragment).publicMethod(args)

    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)

    0 讨论(0)
提交回复
热议问题