【问题标题】:RecyclerView not updating via Live Data ObserverRecyclerView 未通过 Live Data Observer 更新
【发布时间】:2021-08-10 08:58:29
【问题描述】:

我正在尝试在实时数据对象的观察响应中更新 recyclerView 适配器,但它没有更新 UI,如果我调试它,它会开始更新 UI。

看起来添加延迟使其工作或重新分配 recyclerView 项目适配器也可以工作,但我不明白为什么 notifyDataSetChanged 或 notifyItemRangeChanged 不起作用

以下是我正在使用的代码

    adapter = MyAdapter(listOf())
    binding.recyclerView.adapter = adapter


    viewModel = ViewModelProvider(this).get(HomeViewModel::class.java)

    viewModel.data.observe(this, {
        adapter.setData(it)

        // This updates the UI, but this is not the right way to do so 
        //binding.recyclerViewData.adapter = adapter
    })

我更新数据的适配器类

    fun setData(data: MutableList<DataModelRoom>) {
        this.data= data
        notifyItemRangeChanged(0, data.size)
    }

ViewModel部分代码

    var data: MutableLiveData<MutableList<DataModel>> = MutableLiveData()
    

    /* This is part of init method */
    viewModelScope.launch {
        Amplify.Hub.subscribe(HubChannel.DATASTORE) { event ->
            if (event.name == DataStoreChannelEventName.READY.toString()) {
                isAmplifyDataReady.postValue(true)

                data.postValue(repository.getDataFromAmplify())
            }
            Log.i(Logging.TAG_AMPLIFY, "event: $event")
        }

        /* Starting the DataStore Syncing */
        Amplify.DataStore.start(
            { Log.i(Logging.TAG_AMPLIFY, "DataStore started") },
            { Log.e(Logging.TAG_AMPLIFY, "Error starting DataStore", it) }
        )
    }

recyclerView的布局部分

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="152dp"
    android:orientation="horizontal"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textViewView" />

【问题讨论】:

  • 添加活动或片段的完整代码。在哪里设置 recyclerview 和模型观察者。
  • 代码更新,请查看
  • 我们需要设置 Recyclerview 并从 Viewmodel 获取数据的活动代码。您只添加了 Viewmodel 类。

标签: kotlin android-recyclerview aws-amplify android-livedata


【解决方案1】:

我认为你把问题复杂化了。使用ListAdapter&lt;T, K&gt;(包括with the platform 并调用adapter.submitList(pass_the_new_list_here) 并让(必需的)DiffUtil.Callback 处理差异并更新所需内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 2012-08-10
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多