在使用ActivityViewModel和AdapterItemViewModel进行连接时,需要通过数据绑定或事件触发的方式来实现数据传递和更新。
以下是一个使用DataBinding库的示例代码,演示了如何在ActivityViewModel和AdapterItemViewModel之间建立连接:
class ActivityViewModel : ViewModel() {
private val _items = MutableLiveData>()
val items: LiveData> get() = _items
fun loadData() {
// 模拟加载数据
val itemList = listOf(
AdapterItemViewModel("Item 1"),
AdapterItemViewModel("Item 2"),
AdapterItemViewModel("Item 3")
)
_items.value = itemList
}
}
class AdapterItemViewModel(val name: String) {
// 可以添加其他需要的属性和方法
}
activity_main.xml:
MainActivity.kt:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel: ActivityViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.lifecycleOwner = this
binding.viewModel = viewModel
val adapter = Adapter()
binding.recyclerView.adapter = adapter
viewModel.items.observe(this) { items ->
adapter.submitList(items)
}
}
}
class Adapter : ListAdapter(DiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemBinding.inflate(inflater, parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
holder.bind(item)
}
class ViewHolder(private val binding: ItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(item: AdapterItemViewModel) {
binding.item = item
binding.executePendingBindings()
}
}
class DiffCallback : DiffUtil.ItemCallback() {
override fun areItemsTheSame(oldItem: AdapterItemViewModel, newItem: AdapterItemViewModel): Boolean {
return oldItem.name == newItem.name
}
override fun areContentsTheSame(oldItem: AdapterItemViewModel, newItem: AdapterItemViewModel): Boolean {
return oldItem == newItem
}
}
}
item.xml:
通过上述代码,ActivityViewModel和AdapterItemViewModel通过LiveData和DataBinding库进行了连接。当ActivityViewModel中的数据更新时,Adapter会自动更新RecyclerView中的列表项。