【问题标题】:What does notifyDataSetChanged() mean inside an adapter in viewPager2?在 viewPager2 的适配器内 notifyDataSetChanged() 是什么意思?
【发布时间】:2021-06-15 14:49:14
【问题描述】:

我在我的应用程序中使用viewPager2 并添加/删除片段。我正在尝试实现一个在运行时添加/删除选项卡的功能,也许了解notifyDataSetChanged() 的工作原理可能会帮助我实现我的目标。例如:mutableList 可能发生了什么变化?

这是我的适配器(顺便说一句,'titles' 只是电影标题的可变列表):

class DynamicViewPagerAdapter(fragmentActivity: FragmentActivity):
    FragmentStateAdapter(fragmentActivity){

    override fun createFragment(position: Int): Fragment {
        return DynamicFragment()
    }

    override fun getItemCount(): Int {
        return titles.size
    }

    override fun getItemId(position: Int): Long {
        
        return position.toLong()
    }

    override fun containsItem(itemId: Long): Boolean {
        return titles.contains(titles[itemId.toInt()])
    }

    fun addTab(title: String) {
        titles.add(title)
        notifyDataSetChanged()
    }

    fun addTab(index: Int, title: String) {
        titles.add(index, title)
        notifyDataSetChanged()
    }

    fun removeTab(name: String) {
        titles.remove(name)
        notifyDataSetChanged()
    }

    fun removeTab(index: Int) {
        titles.removeAt(index)
        notifyDataSetChanged()
    }
}

【问题讨论】:

    标签: android android-recyclerview notifydatasetchanged android-viewpager2


    【解决方案1】:

    RecyclerView为例,这个widget需要数据与之绑定,也就是数据集,一般是List<xxx>

    RecyclerView: 显示信息列表的View

    ReclerViewAdapter:一个适配器,用于确定每一行的外观

    List<xxx>数据集你想在这个RecyclerView中显示


    假设您已经使用您的RecyclerView 设置了所有内容,然后您修改(添加/删除/更新)您的List<xxx> 的一些数据,此时您必须在您的ReclerViewAdapter 对象上调用notifyDataSetChanged()刷新你的RecyclerView

    这与ViewPager2 相同。只有数据集变为List<Fragment>

    【讨论】:

    • 这回答了我的大部分疑问,但是 recyclerView 在什么时候知道它正在使用哪个列表?它可能在 getItemCount() 函数中,或者可能在适配器之外?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2011-08-12
    • 2017-06-11
    • 2018-03-05
    • 2023-03-27
    • 2012-03-29
    相关资源
    最近更新 更多