亲宝软件园·资讯

展开

Android Jetpack组件支持库

艾阳Blog 人气:0

Android Jetpack之ViewModel、LiveData

Android Jetpack之LifeCycle

一、官方推荐的Jetpack架构

ViewModel是介于View(视图)和Model(数据模型)之间的中间层,能够使视图和数据分离,又能提供视图和数据之间的通信。

LiveData是一个能够在ViewModel中数据发生变化时通知页面刷新UI线程的组件库。

Room是在SQLLite上提供了一层封装。(Android采用SQLLite作为数据库存储)

二、添加依赖

    implementation "androidx.activity:activity-ktx:1.2.0"
    implementation "androidx.fragment:fragment-ktx:1.3.0"

下面的案例,只是简洁的代码片段,大致介绍一下,让大家了解这个架构。具体详细代码及深度原理,请大家自行查阅其他深度讲解文章。

三、创建Repository

StudentRepository

class StudentRepository {
    var studentDao: StudentDao? = null
    constructor(context: Context) {
        val database = MyDatabase.getInstance(context)
        studentDao = database!!.getStudentDao()
    }
    //LiveData集合
    fun getAllStudentsLive(): LiveData<List<Student>> {
        return studentDao!!.getAllStudentsLive()
    }
    fun deleteAllStudents() {
        studentDao!!.deleteAllStudents()
    }
    fun queryAll(): List<Student>? {
        return studentDao!!.queryAll()
    }
    fun insertStudent(vararg student: Student?) {
        studentDao!!.insertStudent(*student)
    }
    fun deleteStudent(vararg student: Student) {
        studentDao!!.deleteStudent(*student)
    }
    fun updateStudent(vararg student: Student) {
        studentDao!!.updateStudent(*student)
    }
}

StudentDao

@Dao
interface StudentDao {
    @Insert
    fun insertStudent(vararg students: Student?)
    @Delete
    fun deleteStudent(vararg students: Student?)
    @Update
    fun updateStudent(vararg students: Student?)
    @Query("SELECT * FROM student")
    fun getAllStudent(): List<Student?>?
    @Query("SELECT * FROM student WHERE id = :id")
    fun getStudentById(id: Int): List<Student?>?
}

Repository类中是关于Dao的操作,getAllStudentsLive()方法返回的是一个LiveData集合。

四、创建ViewModel

StudentViewModel

class StudentViewModel(application: Application) : AndroidViewModel(application) {
	//初始化Repository对象
    private val repository by lazy { StudentRepository(application) } 
	//定义LiveData集合
    private var liveDataStudent: LiveData<List<Student>>? = null
    init {
        liveDataStudent = repository.getAllStudentsLive()
    }
    fun getAllStudentsLive(): LiveData<List<Student>>? {
        viewModelScope.launch(Dispatchers.Default) {
            liveDataStudent = repository.getAllStudentsLive()
        }
        return liveDataStudent
    }
    private fun insertStudent(vararg student: Student) {
        viewModelScope.launch(Dispatchers.Default) {
            repository.insertStudent(*student)
        }
    }
    private fun deleteStudent(vararg student: Student) {
        viewModelScope.launch(Dispatchers.Default) {
            repository.deleteStudent(*student)
        }
    }
    private fun updateStudent(vararg student: Student) {
        viewModelScope.launch(Dispatchers.Default) {
            repository.updateStudent(*student)
        }
    }
    private fun deleteAllStudents() {
        viewModelScope.launch(Dispatchers.Default) {
            repository.deleteAllStudents()
        }
    }
	//以下为DataBinding布局调用的方法-------------------
    fun mInsert() {
        val s1 = Student("zhangsan", 26)
        val s2 = Student("lisi", 18)
        insertStudent(s1, s2)
    }
    fun mClear() {
        deleteAllStudents()
    }
    fun mDelete() {
        var s1 = Student(3)
        deleteStudent(s1)
    }
    fun mUpdate() {
        val s1 = Student(2, "wanger", 21)
        updateStudent(s1)
    }
}

初始化数据库Repository,创建一个livedata集合的属性,并提供对其操作的方法。

五、activity中使用

mainActivity

class MainActivity : AppCompatActivity() {
    private var adapter: StudentRecyclerViewAdapter? = null
    private var listStudent: ArrayList<Student> = ArrayList()
    private var viewModel: StudentViewModel? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //databinding
        val binding = DataBindingUtil.
            setContentView<ActivityMainBinding>(this, R.layout.activity_main)
        //viewmodel
        viewModel = ViewModelProvider(this)[StudentViewModel::class.java]
        binding.studentViewModel = viewModel
        binding.lifecycleOwner = this
        binding.recycleView.layoutManager = LinearLayoutManager(this)
        adapter = StudentRecyclerViewAdapter(listStudent)
        binding.recycleView.adapter = adapter
		//livedata、room
        viewModel!!.getAllStudentsLive()!!.
            observe(this,androidx.lifecycle.Observer {
                adapter!!.students = it
                adapter!!.notifyDataSetChanged()
            })
    }
}

上面案例中,通过ActivityMainBinding获取对应控件,添加对应的逻辑,其次使用getAllStudentsLive方法获取到对应的LiveData,并通过observe监听LiveData集合。

加载全部内容

相关教程
猜你喜欢
用户评论