目录
引言
一、MVVM模式概述
1.1 MVVM模式简介
1.2 MVVM模式的优势
二、MVVM模式的实现
2.1 项目环境配置
dependencies {
// ViewModel and LiveData
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.5.1'
// Data Binding
implementation 'androidx.databinding:databinding-runtime:7.3.1'
// RecyclerView for data display
implementation 'androidx.recyclerview:recyclerview:1.3.1'
}
android {
...
buildFeatures {
dataBinding true
}
...
}
2.2 创建MVVM组件
2.2.1 创建数据模型
data class User(val id: Int, val name: String, val age: Int)
2.2.2 创建数据仓库
class UserRepository {
private val users = mutableListOf<User>()
init {
// 初始化一些用户数据
users.add(User(1, "Alice", 25))
users.add(User(2, "Bob", 30))
users.add(User(3, "Charlie", 28))
}
fun getUsers(): List<User> = users
}
2.2.3 创建ViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class UserViewModel(private val repository: UserRepository) : ViewModel() {
private val _users = MutableLiveData<List<User>>()
val users: LiveData<List<User>> = _users
fun fetchUsers() {
_users.value = repository.getUsers()
}
}
2.2.4 创建布局文件
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="viewModel"
type="com.example.mvvmdemo.viewmodel.UserViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- 使用RecyclerView来展示用户数据 -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
</LinearLayout>
</layout>
2.2.5 创建RecyclerView适配器
// 假设你已经有一个UserAdapter类实现了RecyclerView.Adapter<UserAdapter.ViewHolder>
// 并且ViewHolder中使用了数据绑定
2.3 在Activity中绑定ViewModel
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.mvvmdemo.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel: UserViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.viewModel = viewModel
binding.lifecycleOwner = this
// 观察用户数据变化
viewModel.users.observe(this) { users ->
// 更新RecyclerView的适配器
// adapter.submitList(users)
}
// 初始加载用户数据
viewModel.fetchUsers()
}
}
三、数据绑定技巧
3.1 数据绑定基础
3.2 双向数据绑定
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter name"
android:text="@={viewModel.userName}" />
3.3 观察者模式
3.4 使用表达式语言
<TextView
android:text="@{viewModel.user.name + ', ' + viewModel.user.age + ' years old'}" />