Reputation: 783
I have a FragmentStateAdapter as the adapter of a ViewPager2.
class DefaultFragmentStateAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
var items = listOf<Fragment>()
set(value) {
field = value
notifyDateSetChanged()
}
override fun getItemCount(): Int = items.size
override fun createFragment(position: Int): Fragment = items[position]
}
The adapters item can change depending on the date a user has selected, so it needs to be dynamical.
What happens is that after I call adapter.items = {new_fragments}
current fragment is not reloaded, only after I go to one of the last pages in the ViewPager and return to the first page can I see the updated fragment.
The current fragment does not update when notifyDataSetChanged
is called.
How can I manage to update current displayed fragment?
Upvotes: 21
Views: 7515
Reputation: 783
I had to override the following two methods...
override fun getItemId(position: Int): Long {
return items[position].id
}
override fun containsItem(itemId: Long): Boolean = items.any { it.id == itemId }
... to make it work!
Upvotes: 26
Reputation: 303
The best way that I found was setUserVisibleHint
add this to your fragment
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// load data here
}else{
// fragment is no longer visible
}
}
Upvotes: -1