Android: Multiple snackbars in separate Fragments (ViewPager)

后端 未结 2 1412
梦如初夏
梦如初夏 2021-01-17 17:51

I have a viewpager, with a few fragments of course. Each of these fragments have CoordinatorLayout as parent.

I\'m showing a snackbar for something. The problem is,

2条回答
  •  自闭症患者
    2021-01-17 18:13

    You can use setUserVisibleHint(boolean isVisible) to update fragment visibility (for instance on your ViewPager onPageSelected) and then getUserVisibleHint() on your fragment to show the Snackbar only if the fragment is visible.

    Lets say you have Fragments A, B & C

    Fragment A is visible and so is the Snackbar If Fragment B or C try to open a Snackbar, getUserVisibleHint() will return false and they wont mess up with Fragment A Snackbar.

    Obs. Be careful when doing this with FragmentStatePagerAdapter because you can get NPE keeping references to Fragments and calling setUserVisibleHint() on this references.

    Edit: You don't need setUserVisibleHint() because its already called by the system.

提交回复
热议问题