Update ViewPager dynamically?

后端 未结 20 3101
时光说笑
时光说笑 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条回答
  •  旧时难觅i
    2020-11-22 02:31

    You need change instantiateItem's mFragments element getItemPosition.

        if (mFragments.size() > position) {
            Fragment f = mFragments.get(position);
    
            if (f != null) {
                int newPosition = getItemPosition(f);
                if (newPosition == POSITION_UNCHANGED) {
                    return f;
                } else if (newPosition == POSITION_NONE) {
                    mFragments.set(position, null);
                } else {
                    mFragments.set(newPosition, f);
                }
            }
        }
    

    Based AndroidX FragmentStatePagerAdapter.java, because mFragments's elements position do not change when calling notifyDataSetChanged().

    Source: https://github.com/cuichanghao/infivt/blob/master/library/src/main/java/cc/cuichanghao/library/FragmentStatePagerChangeableAdapter.java

    Example: https://github.com/cuichanghao/infivt/blob/master/app/src/main/java/cc/cuichanghao/infivt/MainActivityChangeablePager.kt

    You can run this project to confirm how to work. https://github.com/cuichanghao/infivt

提交回复
热议问题