How to clear the cached memory of Viewpager with Tablayout
Asked Answered
R

3

6

I just started using ViewPager and Tablayout from Material Design (comes with Android Studio). I created 5 fragments and I am able to use an swipe them as needed.

Based on user selection in Fragment2 I want to remove Fragment3. However, after removing the Tab from the tablayout, when swiping to the 3rd tab (which was the 4th tab before the removal of the 3rd tab) the wrong fragment is displayed - the system has the 3rd Fragment in memory and displayes it. If I destroy that fragment then I get an exception about "Can't change tag of fragment".

How can I tell the system that the 3rd fragment is not to be used or to remove it from memory until I need it and then to reload it to memory.

Ramakrishna answered 9/3, 2016 at 7:50 Comment(1)
@Milan solution worked, with no need to use destoryItem().Ramakrishna
J
14

Are you using FragmentPagerAdapter? If so, you might wanna try FragmentStatePagerAdapter. Because it will destroy the unused fragments. If not, provide some code so we might be able to dive in deeper.

Jews answered 9/3, 2016 at 12:37 Comment(4)
I am using FragmentPagerAdapter. I went to read about FragmentStatePagerAdapter and I understand it does not keep the fragment in memory, but I do not see how will it help, because it does keep the state of the fragment in memory, so it will remember the deleted fragment. Is there a way of telling the ViewPager that the list of the fragment has changed and to ignore the deleted fragment?Ramakrishna
I saw now that it has a method destroyItem(). I'll try itRamakrishna
The destroyItem() has parameters container, position and object. I understand the I can use 'this' as the container, but what about object, where do I get it's value? It is not clear to me how to call this method.Ramakrishna
FragmentStatePagerAdapter works like charm also have good for memory optimization love you for this!Chortle
S
4

I also had the same issue, that was, although I updated the data of the adapter, the view still did not updated! However, I found, once I updated the data for the adapter, and called .notifDataSetChange(), I called .setsAdapter(m_PagerAdapter) AGAIN. That worked for me :) ...

//
// update the data of adapter ...
//
m_PagerAdapter.notifyDataSetChanged();
m_vpgItems.setAdapter(m_PagerAdapter);
Sensibility answered 2/6, 2017 at 1:16 Comment(0)
M
1

set viewpager.offscreenPageLimit to yout fragment count. It should work

Megasporangium answered 13/9, 2022 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.