android - communication problem between two fragments in ViewPage in fragment
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?
After selecting the method, the last thing you need to pay attention to is:
FragmentPagerAdapter and FragmentStatePagerAdapter have differences in managing FragmentPagerAdapter和FragmentStatePagerAdapter在管理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.🎜🎜
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.🎜🎜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