ViewPager2 PagedList DiffUtil FragmentStateAdapter中重建数据不刷新问题
核心根因定位
- Fragment引用错配:
ProductTabPagerAdapter硬编码提前初始化了两个ProductFragment实例存在tabFragments集合中,但FragmentStateAdapter在宿主Fragment跳转、返回触发状态重建时,会通过FragmentManager自动恢复之前存储的Fragment实例,和adapter里硬编码的旧实例属于完全不同的对象。后续调用sendDataToFragment时,取到的是旧的、已脱离生命周期、和当前屏幕上的RecyclerView无绑定关系的Fragment引用,执行setUpListData时的submitList只会在旧Fragment持有的旧适配器上计算DiffUtil,自然不会触发当前屏幕真实RecyclerView的列表更新回调——这也是你观察到“DiffUtil回调触发但RecyclerView的绑定方法未执行”的核心原因。 - 手动设置
retainInstance引发状态混乱:父Fragment和子Fragment都手动开启了retainInstance = true,但ViewPager2 + FragmentStateAdapter本身已经实现了Fragment状态的自动保存与恢复,手动开启该标记会导致Fragment实例不随宿主视图生命周期销毁重建,出现视图层(View、RecyclerView、绑定的Adapter)重新初始化,但拿到的Fragment引用还是旧对象的错配问题。 - 适配器与视图生命周期不匹配:
ProductFragment中productAdapter作为成员变量被直接初始化,当Fragment视图因跳转、返回被销毁重建时,新创建的RecyclerView会绑定新初始化的适配器实例,但因为数据分发时拿的是旧Fragment的引用,新适配器从来没有收到过有效的PagedList数据,始终停留在初始空状态或展示旧缓存。 - LiveData实例被覆盖的问题:
ProductViewModel中的recommendedList、recentList初始值为空的MutableLiveData,在init块执行fetchRecommended/fetchRecent时会创建全新的LiveData实例覆盖原有属性,已经注册的observer会因为旧LiveData被回收,无法接收到后续的数据流回调。
落地解决步骤
重构ViewPager适配器的Fragment获取逻辑
完全移除adapter中硬编码的tabFragments集合,不要提前手动创建Fragment实例,所有Fragment实例的创建完全交给FragmentStateAdapter的标准流程处理;替换获取活跃Fragment的逻辑,不再通过自维护的集合取值,而是通过FragmentManager的标准查找方法,获取和当前ViewPager绑定的真实活跃实例:- 删除
ProductTabPagerAdapter中的internal var tabFragments属性,修改createFragment方法直接按position创建对应ProductFragment实例返回:override fun createFragment(position: Int): Fragment { return ProductFragment.newInstance( when(position) { POSITION_TAB_RECOMMENDED -> ProductTabFragment.POSITION_TAB_RECOMMENDED else -> ProductTabFragment.POSITION_TAB_RECENT } ) } - 修改
sendDataToFragment方法,通过FragmentStateAdapter约定的Fragment TAG格式,查找当前真实存在的活跃Fragment:private fun sendDataToFragment(fragmentPosition: Int, productList: PagedList<Product>?) { // FragmentStateAdapter创建Fragment时会按固定规则设置TAG,格式为"f{position}" val fragmentTag = "f$fragmentPosition" val activeFragment = childFragmentManager.findFragmentByTag(fragmentTag) as? ProductFragment activeFragment?.setUpListData(productList) }
- 删除
移除所有冗余的
retainInstance配置
把ProductTabFragment和ProductFragment的onAttach方法中设置retainInstance = true的代码全部删除,让Fragment的生命周期完全跟随宿主视图的生命周期流转,避免实例缓存导致的引用错配。优化ProductFragment的适配器生命周期管理
调整适配器的初始化和数据缓存逻辑,保证不管Fragment视图是首次创建还是返回时重建,数据都能正常提交给和当前RecyclerView绑定的适配器:- 删除成员变量直接初始化的适配器代码,改为和视图同生命周期管理:
class ProductFragment : Fragment() { // 缓存最新的PagedList数据,避免视图重建时丢失 private var latestPagedList: PagedList<Product>? = null private var productAdapter: ProductPagedListAdapter? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 视图创建时初始化适配器,和当前RecyclerView绑定 productAdapter = ProductPagedListAdapter() view.findViewById<RecyclerView>(R.id.productList)?.apply { layoutManager = LinearLayoutManager(context) adapter = productAdapter } // 视图初始化完成后,主动把缓存的最新数据提交给适配器 latestPagedList?.let { productAdapter?.submitList(it) } } fun setUpListData(data: PagedList<Product>?) { latestPagedList = data // 只有当适配器和当前视图绑定了,才直接提交,否则先缓存 productAdapter?.submitList(data) } override fun onDestroyView() { super.onDestroyView() // 视图销毁时清空适配器引用,避免内存泄漏 productAdapter = null } }修正ViewModel中的PagedList初始化逻辑
不要在init块中创建新的LiveData实例覆盖原有属性,直接在属性定义阶段通过LivePagedListBuilder构建好常驻的LiveData实例,避免observer因为LiveData实例被替换而收不到数据:class ProductViewModel : ViewModel() { // 直接构建常驻的LiveData,不要后续覆盖 val recommendedList: LiveData<PagedList<Product>> = LivePagedListBuilder<Int, Product>( object : DataSource.Factory<Int, Product>() { override fun create(): DataSource<Int, Product> { return ProductDataSource(type = "recommended") } }, PagedList.Config.Builder() .setPageSize(ProductDataSource.PAGE_LIMIT) .setEnablePlaceholders(false) .build() ).build() val recentList: LiveData<PagedList<Product>> = LivePagedListBuilder<Int, Product>( object : DataSource.Factory<Int, Product>() { override fun create(): DataSource<Int, Product> { return ProductDataSource(type = "recent") } }, PagedList.Config.Builder() .setPageSize(ProductDataSource.PAGE_LIMIT) .setEnablePlaceholders(false) .build() ).build() fun resetPaginationData() { recommendedList.value?.dataSource?.invalidate() recentList.value?.dataSource?.invalidate() } }
验证要点
- 触发数据源失效重新拉取时,确认LiveData能正常发出新的PagedList值
- 确认
sendDataToFragment获取到的Fragment是当前附着在ViewPager上的活跃实例,不是已销毁的旧对象 - 确认执行
submitList时,适配器和当前屏幕上展示的RecyclerView是绑定关系,不存在跨实例提交的情况
内容的提问来源于stack exchange,提问作者GGH
相关产品推荐
相关产品推荐

