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?
为情所困2017-05-16 13:23:02
As the questioner said, if it was just the interaction between Toolbar and Fragment, it would be relatively simple:
Activity#setActionBar(android.widget.Toolbar)
或者 AppCompatActivity#setSupportActionBar(android.support.v7.widget.Toolbar)
Fragment#setHasOptionsMenu(boolean)
Fragment
The 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:
greenrobot/EventBus
AndroidKnife/RxBus
square/otto
The second is LocalBroadcastManager, reference:
Android Developer Reference # android.support.v4.content.LocalBroadcastManager
Once again, Fragment uses Activity to interact, reference:
Android Developer Guide # Communicating with Other Fragments
Android Developer Guide # Fragment
Finally, it is implemented directly through TargetFragment, related functions:
Fragment#setTargetFragment(android.app.Fragment, int)
Fragment#getTargetFragment()
Fragment#getTargetRequestCode()
After selecting the method, the last thing you need to pay attention to is:
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.🎜🎜is different. Therefore, what needs to be considered is when
FragmentPagerAdapter
andFragmentStatePagerAdapter
have differences in managingFragmentPagerAdapter
和FragmentStatePagerAdapter
在管理Fragment
时是有差别: 回收Fragment
的处理是不同的. 因此, 需要考虑的是, 当Fragment
: the processing of recycling
世界只因有你2017-05-16 13:23:02
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