Fragment in TabLayout only load when user slide Android

前端 未结 2 1542
旧巷少年郎
旧巷少年郎 2021-01-05 07:06

Hi I\'m making an app with A fragment and few child fragment inside it using tablayout and viewpager. The problem is all

相关标签:
2条回答
  • 2021-01-05 07:48
    @Override public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }
    

    you could use above method within your fragment that is within your ViewPager Adapter

    if(isVisibleToUser){//dosomething when the fragment is visible}
    else{//dosomething else.}
    

    be aware to do not initialize views there or anything rather, init your views within onViewCreated and call the method that you wanna execute on setUserVisibleHint. another ugly way is to add a scroll listener to your ViewPager and get the current item position and trigger an action that is within the fragment. to get the fragment from the ViewPager Adapter you can do such :

     MyFragment frag = (MyFragment) pager.getAdapter().instantiateItem(pager, position);
    

    then you could call a method that is within MyFragment

    0 讨论(0)
  • 2021-01-05 07:52

    The Viewpager by default loads the adjacent fragment to ensure make the app smooth, so that when the user swipe to the fragments (already loaded) it is there. To change is default behavior, use viewpager.setOffscreenPageLimit(int limit) where limit is how many fragment next to the one you are on will be preloaded. Hope this helps

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