android-fragments 具有片段数据集更改的ViewPager2

4smxwvx5  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(148)

我正在尝试使用viewpager2创建选项卡布局,其中包含fragmentrecylerview以显示数据。当使用虚拟数据时,它工作正常,但当我需要更新recylerview中的数据时,数据集没有更改。这就是我所尝试的
用于刷新数据

viewPagerAdapter.refreshOfflineFragAdapter(1,expiryOfflineList,trendingOfflineList)
 fun refreshOnlineFragAdapter(index: Int, expirySoon: ArrayList<OnlineOfferAPIResult>?,trending:ArrayList<OnlineOfferAPIResult>?) {
      fragmentList[index] = OfferFrag.newInstance(expirySoon,trending)
      notifyItemChanged(index)

 }

第二次尝试

viewPagerAdapter.refreshOfflineFragAdapter(1,OfferFrag.newInstance(expiryOfflineList,trendingOfflineList))
 fun refreshOfflineFragAdapter(index: Int, fragment: OfferFrag) {
      fragmentList[index] = fragment
      notifyItemChanged(index)
 }

这是viewpager的片段类

class OfferFrag:BaseFragment() {

      companion object{
           private val ExpirySoonOffers = "expirySoonoffers"
           private val TrendingOffers = "trendingOffers"

           fun newInstance(expirySoonoffers:ArrayList<OnlineOfferAPIResult>?,trendingOffers:ArrayList<OnlineOfferAPIResult>?): OfferFrag {
                val args = Bundle()
                val fragment = OfferFrag()
                args.putParcelableArrayList(ExpirySoonOffers,expirySoonoffers)
                args.putParcelableArrayList(TrendingOffers,trendingOffers)
                fragment.arguments = args
                return fragment
           }
      }
      override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
           super.onViewCreated(view, savedInstanceState)
           if(arguments!=null){
                if (this.requireArguments().containsKey(ExpirySoonOffers)) {
                     expiringOfferList = this.requireArguments().getParcelableArrayList<OnlineOfferAPIResult>(ExpirySoonOffers) as ArrayList<OnlineOfferAPIResult>
                }
                if (this.requireArguments().containsKey(TrendingOffers)) {
                     trendingOfferList?.value = this.requireArguments().getParcelableArrayList<OnlineOfferAPIResult>(TrendingOffers) as ArrayList<OnlineOfferAPIResult>
                }
           }
      }

现在,当我调试代码时,我发现当再次调用newInstance时,它有值,但当调用onCreateView时,它将参数数据取为空。即,trendingOfferListexpiryOfferListonViewCreated中为空。
请如果任何人有任何解决这个问题的办法。

kzipqqlq

kzipqqlq1#

创建片段是一项开销很大的操作,如果您有想要更新的UI,我建议您通知片段有关UI更改的信息,因为您已经引用了片段:

viewPagerAdapter.refreshOfflineFragAdapter(1,expiryOfflineList,trendingOfflineList)
 fun refreshOnlineFragAdapter(index: Int, expirySoon: ArrayList<OnlineOfferAPIResult>?,trending:ArrayList<OnlineOfferAPIResult>?) {
      fragmentList[index].update(expirySoon,trending)

 }

在该片段中,只需将新数据设置为UI元素

相关问题