我是靠谱客的博主 单身花瓣,最近开发中收集的这篇文章主要介绍Jetpack系列-Room+ViewModel+LiveData+ViewBinding实现MVVM,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Room能和LiveData很好的结合实现MVVMRoom可以利用LiveData的观察者模式,感知Lifecyle的状态,实现数据驱动UI,避免MVP模式下更新UI需要大量回调接口的繁琐。

下面整合RoomViewModelLiveDataViewBinding,实现一个简单的MVVM示例项目。

1 引入依赖

引入ViewModel依赖:

dependencies {
    
    def lifecycle_version = "2.4.1"
    
    // ViewModel
    implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
    ...   
 }

引入Room依赖:

dependencies {
    ...
    def room_version = "2.4.2"

    // Room
    implementation "androidx.room:room-runtime:$room_version"
    kapt "androidx.room:room-compiler:$room_version"
    ...
}

添加kapt支持:

plugins {
    ...
    id 'kotlin-kapt'
}

开启ViewBinding

android {   
    ...
    viewBinding{
        enabled = true
    }
}

2 Model层

创建实体类Book

@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

@Dao
interface BookDao {
    
    @Insert
    fun insert(book: Book)
    
    @Query("select * from Book")
    fun queryAll(): LiveData<MutableList<Book>>
    
}

创建DataBase

@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层

class 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层

class 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

<?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:

<?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>

实现RecyclerViewAdapter

class 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更新:

class 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所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部