Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] android – FragmentStateAdapter for ViewPager2 notifyItemChanged not working as expected

Posted on November 11, 2022 By

Solution 1 :

FragmentStateAdapter uses item IDs to determine if a fragment has already been created and reuses already created ones. By default, an item ID is the item’s position. You can override getItemId and containsItem to provide your own unique IDs based on positions and dates, then it will ask for a new fragment when the date changes.

Solution 2 :

When you call notifyItemChanged for FragmentStateAdapter it call ensureFragment(position)that restores the fragment if it has already been created

 private void ensureFragment(int position) {
    long itemId = getItemId(position);
    if (!mFragments.containsKey(itemId)) {
        // TODO(133419201): check if a Fragment provided here is a new Fragment
        Fragment newFragment = createFragment(position);
        newFragment.setInitialSavedState(mSavedStates.get(itemId));
        mFragments.put(itemId, newFragment);
    }
}

Try to override onBindViewHolder and set Date to fragment

   override fun onBindViewHolder(
    holder: FragmentViewHolder,
    position: Int,
    payloads: MutableList<Any>
) {
    super.onBindViewHolder(holder, position, payloads)
    val fragment: EEditionListingFragment? = fragmentManager.findFragmentByTag("f$position") as EEditionListingFragment?
    fragment.updateDate(date)
}

Solution 3 :

The fragment put to the mFragment in FragementStateAdapter.class is managed by the

void placeFragmentInViewHolder(@NonNull final FragmentViewHolder holder)

method, which is package private and we do not have access and in this method the fragment is added to the mFragment manager with tag "f" + holder.getItemId() which is the same as "f" + position.

        scheduleViewAttach(fragment, container);
        mFragmentManager.beginTransaction()
                .add(fragment, "f" + holder.getItemId())
                .setMaxLifecycle(fragment, STARTED)
                .commitNow();
        mFragmentMaxLifecycleEnforcer.updateFragmentMaxLifecycle(false);

For this reason, we can override the onBindViewHolder method while a fragement shall be displayed.

@Override
public void onBindViewHolder(@NonNull FragmentViewHolder holder, int position, @NonNull List<Object> payloads) {
    super.onBindViewHolder(holder, position, payloads);
    if (position == 0) {

        String fragmentTag = "f" + holder.getItemId();
        Log.v(TAG,"fragmentTag is : " + fragmentTag);
        MyFragment fragment0 = (MyFragment) this.mFragmentManger.findFragmentByTag(fragmentTag);

        if (fragment0 != null) {
            Log.v(TAG,"onBindViewHolder updating fragment ...");
            // do what ever you want to update the MyFragment 
            fragment0.update(payloads);
        } else {
            Log.v(TAG,"onBindViewHolder called, but fragment0 is null!");
        }
    }
} 

In my case the this.mFragmentManager is cashed through the constructor.

public MyFragmentStateAdapter(@NonNull Fragment fragment) {
        super(fragment); // this calls the fragment.getChildFragmentManager().
        this.mFragmentManger = fragment.getChildFragmentManager();
}

And the createFragment() is:

@NonNull
@Override
public Fragment createFragment(int position) {
    if(position == 0){
        if (this.fragment0 == null) {
            this.fragment0 = MyFragment.getInstance();
        }
        return this.fragment0;
    } else {
        Log.v(TAG, "position " + position + " is called");
        return null;
    }
}

Finally, call the update in somewhere else to trigger the update:

ViewPager2.getAdapter().notifyItemChanged(0, null); 
// 0 is the fragment position of the fragment0 and null is payload.

Problem :

I am using ViewPager2 with FragmentStateAdapter and i am calling notifyItemChanged(position). But as expected createFragment method not calling again. Is it is the intended behavior or bug, what should I do

READ  [FIXED] xamarin.forms - Zebra Barcode Scanner SDK : Xamarin Forms
Powered by Inline Related Posts

My Code is

    class EEditionPagerAdapter(
    fragmentManager: FragmentManager, lifecycle: Lifecycle, private var date: String
    ) : FragmentStateAdapter(fragmentManager, lifecycle) {

    private var menuList = emptyList<EEditionMenu>()

    override fun getItemCount(): Int = menuList.size

    override fun createFragment(position: Int): Fragment {
        val menu = menuList[position]
        return EEditionListingFragment.newInstance(menu, date)
    }

    fun submitList(list: List<EEditionMenu>) {
        menuList = list
        notifyItemRangeChanged(0, menuList.size)
    }

    fun changeDate(date: String, position: Int){
        this.date = date
        notifyItemChanged(position)
    }
}

Comments

Comment posted by Karthick Ramanathan

So what should I do to refresh the current page fragment

Comment posted by kalugin1912

Сompleted the answer

Comment posted by slott

Nice – odd though that there is no get method for this if the truly want to bridge the gap between viewpager and recyclerview…

Comment posted by StenSoft

@slott The bridge is using your own item IDs

Android Tags:android, android-viewpager2

Post navigation

Previous Post: [FIXED] android – How to pass data by Back Button, Kotlin
Next Post: [FIXED] Project with external module issue in android studio 3.6

Related Posts

[FIXED] android – How do I fix “emulator: ERROR: No AVD specified. Use ‘@foo’ or ‘-avd foo’ to launch a virtual device named ‘foo'” Android
[FIXED] How do I get information (name) of the user who scan qr code with an android app that I build? Android
[FIXED] android – Error: Program type already present: com.google.gson.JsonNull how to find the duplicated lib Android
[FIXED] Android WebView UserAgent Android
[FIXED] java – How can I refresh my Reclycler adapter onDismiss? Android
[FIXED] java – Cannot resolve method ‘getJSModule’ in Android Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • Can VPN be traced by police?
  • Where were Kaiser-Frazer cars built?
  • How do you make gold rose gold paint?
  • What are the newest type of dentures?
  • Can you wear joggers as dress pants?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme