[英]FragmentPagerAdapter shows wrong fragment after data change
I have a simple FragmentPagerAdaper
, and I have overriden the getItem
and getCount
methods.我有一个简单的FragmentPagerAdaper
,并且覆盖了getItem
和getCount
方法。
Everything works fine until I change the data.一切正常,直到我更改数据。
Even after calling notifyDataSetChanged
, the ViewPager
is showing the old fragment, even tough I am not returning it in getItem
.即使在调用notifyDataSetChanged
, ViewPager
也会显示旧片段,即使我没有在getItem
返回它。
Kotlin Code:科特林代码:
private inner class Adapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {
override fun getItem(position: Int): Fragment {
when (getType(position)) {
Constants.CHAT_TYPE_PARTNER -> {
return TaskChatFragment.newInstance(...)
}
Constants.CHAT_TYPE_SUPPORT -> {
return TaskChatFragment.newInstance(...)
}
}
throw IllegalArgumentException("invalid position " + position)
}
fun getPosition(type: Int) =
if (type == Constants.CHAT_TYPE_SUPPORT && shouldShowPartnerChat()) 1 else 0
override fun getCount(): Int {
var count = 0
if (shouldShowPartnerChat()) count++
if (shouldShowSupportChat()) count++
return count
}
}
I needed to override getItemId
in addition to the 2 methods, since I was changing the position of a fragment returned by getItem
.除了 2 个方法之外,我还需要覆盖getItemId
,因为我正在更改getItem
返回的片段的位置。 As mentioned in the docs:如文档中所述:
long getItemId (int position)
Return a unique identifier for the item at the given position.返回给定位置的项目的唯一标识符。
The default implementation returns the given position.默认实现返回给定的位置。 Subclasses should override this method if the positions of items can change.如果项目的位置可以改变,子类应该覆盖这个方法。
/**
* We need to override this as positions of items may change.
*
* Like when the partner conv is hidden.
*/
override fun getItemId(position: Int) = getType(position).toLong()
I figured this out after debugging using breaking points, and realized that getItem
is not being called after calling notifyDataSetChanged
我想通了这一点用的断点调试后,并意识到getItem
没有被调用后调用notifyDataSetChanged
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.