Room
能和LiveData
很好的结合实现MVVM
,Room
可以利用LiveData
的观察者模式,感知Lifecyle
的状态,实现数据驱动UI,避免MVP
模式下更新UI需要大量回调接口的繁琐。
下面整合Room
、ViewModel
、LiveData
、ViewBinding
,实现一个简单的MVVM示例项目。
1 引入依赖
引入ViewModel
依赖:
复制代码
1
2
3
4
5
6
7
8
9
10dependencies { def lifecycle_version = "2.4.1" // ViewModel implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version") ... }
引入Room
依赖:
复制代码
1
2
3
4
5
6
7
8
9
10
11dependencies { ... def room_version = "2.4.2" // Room implementation "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-compiler:$room_version" ... }
添加kapt
支持:
复制代码
1
2
3
4
5
6plugins { ... id 'kotlin-kapt' }
开启ViewBinding
:
复制代码
1
2
3
4
5
6
7
8android { ... viewBinding{ enabled = true } }
2 Model层
创建实体类Book
:
复制代码
1
2
3
4
5
6
7
8
9
10
11@Entity data class Book constructor( @field:ColumnInfo(name = "name") var name: String, @field:ColumnInfo(name = "author") var author: String ) { @PrimaryKey(autoGenerate = true) var bookId: Int = 0 }
创建DAO
:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12@Dao interface BookDao { @Insert fun insert(book: Book) @Query("select * from Book") fun queryAll(): LiveData<MutableList<Book>> }
创建DataBase
:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22@Database(entities = [Book::class], version = 1, exportSchema = false) abstract class AppDataBase : RoomDatabase() { companion object { private var instance: AppDataBase? = null fun getInstance(context: Context): AppDataBase? { synchronized(AppDataBase::class.java) { if (instance == null) { //初始化Room 单例 instance = Room.databaseBuilder(context, AppDataBase::class.java, "MsDB") .allowMainThreadQueries() .build() } } return instance } } abstract fun bookDao(): BookDao }
3 Repository层
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21class BookRepository(context: Context) { private var allBook: LiveData<MutableList<Book>>? = null private var bookDao: BookDao? = null init { val dataBase = AppDataBase.getInstance(context) bookDao = dataBase?.bookDao() allBook = bookDao?.queryAll() } fun insert(book: Book) { bookDao?.insert(book) } fun queryAll(): LiveData<MutableList<Book>>? { return bookDao?.queryAll() } }
4 ViewModel层
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17class BookViewModel(application: Application) : AndroidViewModel(application) { private var bookRepository: BookRepository? = null init { bookRepository = BookRepository(application) } fun insert(book: Book){ bookRepository?.insert(book) } fun queryAll():LiveData<MutableList<Book>>?{ return bookRepository?.queryAll() } }
5 View层
activity_main.xml中添加一个RecyclerView
:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
创建item布局item_book.xml:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:gravity="center_vertical" android:orientation="horizontal"> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="20dp" android:textColor="@color/black" android:textSize="16sp" /> <TextView android:id="@+id/tv_author" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/darker_gray" android:textSize="14sp" /> </LinearLayout>
实现RecyclerView
的Adapter
:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21class BookAdapter(private val allBook: MutableList<Book>) : RecyclerView.Adapter<BookAdapter.MyHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder { val binding = ItemBookBinding.inflate(LayoutInflater.from(parent.context)) return MyHolder(binding) } override fun onBindViewHolder(holder: MyHolder, position: Int) { Log.d("---MS---", "onBindViewHolder: $position ${allBook[position].name}") holder.binding.tvName.text = allBook[position].name holder.binding.tvAuthor.text = allBook[position].author } override fun getItemCount() = allBook.size inner class MyHolder(val binding: ItemBookBinding) : RecyclerView.ViewHolder(binding.root) }
在Activity
中进行UI更新:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44class MainActivity : AppCompatActivity() { private var viewModel: BookViewModel? = null private var binding: ActivityMainBinding? = null private var adapter: BookAdapter? = null private val allBook by lazy { mutableListOf<Book>() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //绑定布局 binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding?.root) //初始化RecyclerView binding?.recyclerView?.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) adapter = BookAdapter(allBook) binding?.recyclerView?.adapter = adapter //创建ViewModel viewModel = ViewModelProvider( this, ViewModelProvider.AndroidViewModelFactory.getInstance(application) )[BookViewModel::class.java] //监听LiveData数据变化 viewModel?.queryAll()?.observe(this) { allBook.clear() allBook.addAll(it) adapter?.notifyDataSetChanged() } //模拟添加数据 thread { for (i in 0..100) { Thread.sleep(1000) viewModel?.insert(Book("书名$i", "作者$i")) } } } }
最后
以上就是单身花瓣最近收集整理的关于Jetpack系列-Room+ViewModel+LiveData+ViewBinding实现MVVM的全部内容,更多相关Jetpack系列-Room+ViewModel+LiveData+ViewBinding实现MVVM内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复