我想观察一个MutableList,这样当项目被添加或从MutableList中删除时,DiffUtil将更新RecycerView。我认为更新列表的最佳方法是使用LiveData,但我无法添加或删除MutableList中的项目。
我一直在关注下面的代码实验室,试图帮助我。
https://codelabs.developers.google.com/codelabs/kotlin-android-training-diffutil-databinding/#4
主要活动
class MainActivity : AppCompatActivity() {
val list: LiveData<MutableList<User>>? = null
var mAdapter = RVAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addUser()
val rv = findViewById<RecyclerView>(R.id.recycler_view)
rv.apply {
LayoutManager = LinearLayoutManager(baseContext, LinearLayoutManager.VERTICAL, false)
adapter = mAdapter
}
list?.observe(viewLifeCycleOwner, Observer {
it?.let {
mAdapter.submitList(it)
}
}
}
private fun addUser() {
list.add(User("Shawn", 1)
list.add(User("Shannon", 2)
list.add(User("Steve", 3)
list.add(User("Sara", 4)
}
}
用户数据类
data class User(val name: String, val accountNumber: Int) {
}
适配器
class RVAdapter : ListAdapter<User, RVAdapter.ViewHolder>(MyDiffCallback()) {
class MyDiffCallback : DiffUtil.ItemCallback<User>() {
override fun areItemsTheSame(oldItem: User, newItem: User): Boolean {
return oldItem.name == newItem.name
}
override fun areContentsTheSame(oldItem: User, newItem: User): Boolean {
return oldItem == newItem
}
}
...
}
这是我目前的代码,我无法添加或删除列表中的项目,并且ViewLifecycleOwner未定义。
首先,您需要初始化您的livedata并将您的列表发布到它。您可以查看下面的示例
class MainActivity : AppCompatActivity() {
val list = MutableLiveData<List<User>?>()
var mAdapter = RVAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addUser()
val rv = findViewById<RecyclerView>(R.id.recycler_view)
rv.apply {
LayoutManager = LinearLayoutManager(baseContext, LinearLayoutManager.VERTICAL, false)
adapter = mAdapter
}
list.observe(this, Observer {
it?.let {
mAdapter.submitList(it)
}
}
}
private fun addUser() {
val newList = mutableListOf<User>()
newList.add(User("Shawn", 1)
newList.add(User("Shannon", 2)
newList.add(User("Steve", 3)
newList.add(User("Sara", 4)
list.postValue(newList)
}
}
这可能会有所帮助。你可以实现你想要的,但你总是必须将LiveData和ViewModel结合起来才能获取数据并更新它。谷歌建议这样做。
class MainActivity : AppCompatActivity() {
val list: LiveData<MutableList<User>> = MutableLiveData<List<User>>().apply{
postValue(mutableListOf<User>())
}
var mAdapter = RVAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addUser()
val rv = findViewById<RecyclerView>(R.id.recycler_view)
rv.apply {
LayoutManager = LinearLayoutManager(baseContext, LinearLayoutManager.VERTICAL, false)
adapter = mAdapter
}
list?.observe(viewLifeCycleOwner, Observer {
it?.let {
mAdapter.submitList(it)
}
}
}
private fun addUser() {
val userList = list.getValue()
userList .add(User("Shawn", 1)
userList .add(User("Shannon", 2)
userList .add(User("Steve", 3)
userList .add(User("Sara", 4)
list.postValue(userList)
}
private fun editUser() {
val userList = list.getValue()
userList.add(User("Shawn", 21)
list.postValue(userList)
}
}