Update ViewPager dynamically?

后端 未结 20 3081
时光说笑
时光说笑 2020-11-22 02:00

I can\'t update the content in ViewPager.

What is the correct usage of methods instantiateItem() and getItem() in FragmentPagerAdapter class?

I was using onl

20条回答
  •  情话喂你
    2020-11-22 02:35

    I had a similar problem but don't want to trust on the existing solutions (hard coded tag names etc.) and I couldn't make M-WaJeEh's solution work for me. Here is my solution:

    I keep references to the fragments created in getItem in an array. This works fine as long as the activity is not destroyed due to configurationChange or lack of memory or whatever (--> when coming back to the activity, fragments return to their last state without 'getItem' being called again and thus without updating the array).

    To avoid this problem I implemented instantiateItem(ViewGroup, int) and update my array there, like this:

            @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Object o = super.instantiateItem(container, position);
            if(o instanceof FragmentX){
                myFragments[0] = (FragmentX)o;
            }else if(o instanceof FragmentY){
                myFragments[1] = (FragmentY)o;
            }else if(o instanceof FragmentZ){
                myFragments[2] = (FragmentZ)o;
            }
            return o;
        }
    

    So, on the one hand I'm happy that I found a solution that works for me and wanted to share it with you, but I also wanted to ask whether somebody else tried something similar and whether there is any reason why I shouldn't do it like that? So far it works very good for me...

提交回复
热议问题