android - communication problem between two fragments in ViewPage in fragment
PHP中文网
PHP中文网 2017-05-16 13:21:02
0
2
675

In the main fragment, there is a toolbar with a ViewPager underneath, and a fragment inside the ViewPager. Now I want to operate the button on the toolbar and change the data in the Fragment in the ViewPager. Is there any good communication method?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
为情所困

As the questioner said, if it was just the interaction between Toolbar and Fragment, it would be relatively simple:

  1. Activity#setActionBar(android.widget.Toolbar) 或者 AppCompatActivity#setSupportActionBar(android.support.v7.widget.Toolbar)

  2. Fragment#setHasOptionsMenu(boolean)

  3. FragmentThe internal ActionBar is processed the same as Activity, see the picture below:

p.s. Below the dividing line is the relevant information about the interaction between Fragments.


The simplest way is EventBus, optional libraries:

  1. greenrobot/EventBus

  2. AndroidKnife/RxBus

  3. square/otto

The second is LocalBroadcastManager, reference:

  • Android Developer Reference # android.support.v4.content.LocalBroadcastManager

Once again, Fragment uses Activity to interact, reference:

  1. Android Developer Guide # Communicating with Other Fragments

  2. Android Developer Guide # Fragment

Finally, it is implemented directly through TargetFragment, related functions:

  1. Fragment#setTargetFragment(android.app.Fragment, int)

  2. Fragment#getTargetFragment()

  3. Fragment#getTargetRequestCode()


After selecting the method, the last thing you need to pay attention to is:

FragmentPagerAdapter and FragmentStatePagerAdapter have differences in managing FragmentPagerAdapterFragmentStatePagerAdapter在管理Fragment时是有差别: 回收Fragment的处理是不同的. 因此, 需要考虑的是, 当Fragment: the processing of recycling

is different. Therefore, what needs to be considered is when
is recycled and appears again When on the screen, how should the App handle (save & restore) the interactive relationship between Fragments mentioned in the question.🎜🎜
世界只因有你

If you want to exchange data between two Fragments, you can use EventBus

If you are just operating the toolbar to switch fragments, load the fragment and pass in the data directly

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template