如何解决带列表的LiveData
我想观察一个MutableList,以便在从MutableList中添加或删除项目时,DiffUtil将更新RecycerView。我认为更新列表的最佳方法是使用LiveData,但无法从MutableList中添加或删除项目。
我一直在下面的代码实验室中尝试并帮助我。
https://codelabs.developers.google.com/codelabs/kotlin-android-training-diffutil-databinding/#4
主要活动
socket.id
用户数据类
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) {
}
这是我目前的代码,我无法在列表中添加或删除项目,并且ViewLifecycleOwner未定义。
解决方法
首先,您需要初始化实时数据并将其发布到该数据。您可以检查以下示例
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结合使用以获取和更新数据。 Google建议采用这种方式。
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,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)
}
}