-1

I have a simple FragmentPagerAdaper, and I have overriden the getItem and getCount methods.

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.

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
    }
}
Vedant Agarwala
  • 18,146
  • 4
  • 66
  • 89

1 Answers1

0

I needed to override getItemId in addition to the 2 methods, since I was changing the position of a fragment returned by 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

Community
  • 1
  • 1
Vedant Agarwala
  • 18,146
  • 4
  • 66
  • 89