Jetpack组件:ViewModel,LiveData,DataBinding简单实践,附Demo

1.基本概念

1.1组件介绍

ViewModel: 存放和管理UI界面就是View中的数据
LiveData: 给数据添加一个观察者,当数据发生变动时,自动刷新UI界面上的数据
DataBinding: 管理UI界面的控件,就不需要要findViewById之类,同时可以将数据和一定操作回绑到view中
通过上面这三个组件就能够使activity或fragment只需要专注业务逻辑本身

1.2Demo介绍

1.2.1UI设计

一个textView显示一个数值
两个Button,分别实现对数值进行加一和减一
Jetpack组件:ViewModel,LiveData,DataBinding简单实践,附Demo_第1张图片

1.2.2项目结构

Jetpack组件:ViewModel,LiveData,DataBinding简单实践,附Demo_第2张图片

2.修改build.gradle(Module:app)文件

启动dataBinding:dataBinding.enabled = true
添加依赖:implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
修改之后代码如下:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.kotlinviewmodeldemo"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        //启动dataBinding
        dataBinding.enabled = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    //添加依赖
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
}

3.继承ViewModel创建自己的ViewModel

package com.example.kotlinviewmodeldemo

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class SelfViewModel : ViewModel() {
    //声明一个私有变量number
    private val _number: MutableLiveData<Int> by lazy {
        //MutableLiveData是LiveData的一个容器,Int是数据类型
        MutableLiveData<Int>().also {
            it.value = 0
        }
    }
    val number: MutableLiveData<Int> get() = _number

    fun modifyNumber(n: Int) {
        _number.value = _number.value?.plus(n)
    }
}

4.修改xml文件

4.1选中constraintlayout,会出现一个黄色的小灯泡,点击它

Jetpack组件:ViewModel,LiveData,DataBinding简单实践,附Demo_第3张图片

4.2点击,转成binging Layout文件

Jetpack组件:ViewModel,LiveData,DataBinding简单实践,附Demo_第4张图片

4.3在xml文件中添加代码

引用变量:android:text="@{String.valueOf(data.number)} //data.number是Int型,要先转化成字符串 "
引用方法:android:onClick="@{()->data.modifyNumber(-1)} //这是一个监听事件,引用方法"

4.4完整的activity_main.xml文件如下

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <data>
        <variable
            name="data"
            type="com.example.kotlinviewmodeldemo.SelfViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="60sp"
            android:text="@{String.valueOf(data.number)}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.25" />

        <Button
            android:id="@+id/buttonLess"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="80dp"
            android:text="-1"
            android:onClick="@{()->data.modifyNumber(-1)}"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="@+id/guideline"
            app:layout_constraintTop_toBottomOf="@+id/textView" />

        <Button
            android:id="@+id/buttonPlus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="80dp"
            android:text="+1"
            android:onClick="@{()->data.modifyNumber(1)}"
            app:layout_constraintEnd_toStartOf="@+id/guideline"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

5.配置activity

package com.example.kotlinviewmodeldemo

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.example.kotlinviewmodeldemo.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        setContentView(R.layout.activity_main)

        //ViewModel绑定
        val selfViewModel: SelfViewModel = ViewModelProvider(this).get(SelfViewModel::class.java)

        //dataBinding 将View上的控件绑定到binding
        val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        binding.data = selfViewModel //给xml文件中的data赋值
        binding.lifecycleOwner = this //绑定生命周期
    }
}

6.github源码

https://github.com/YDDUONG/jetpack_ViewModel_LiveData_DataBinding

你可能感兴趣的:(Android)