效果:
一 依赖
implementation ‘com.google.android.material:material:1.0.0’
implementation ‘androidx.lifecycle:lifecycle-extensions:2.2.0’
二 启用
在build.gradle(app)中的testInstrumentationRunner上面添加一句
dataBinding.enabled= true
三 ViewModel
java:
private MutableLiveData<Integer> number;
public MutableLiveData<Integer> getNumber() {
if (number == null) {
number = new MutableLiveData<>();
number.setValue(0);
}
return number;
}
public void changednumber(Int newnumber) {
number.setValue(number.getValue()+newnumber);
}
kotlin:
private val _number:MutableLiveData<Int> by lazy { MutableLiveData<Int>(0) }//初始值为0
var number=_number
fun changednumber(a:Int){
_number.value= _number.value?.plus(a)
}
四 xml绑定
主要内容:
<data>
<variable
name="vm"
type="com.example.mutablelivedata.MyViewModel" />
</data>
android:text="@{String.valueOf(vm.number)}"
android:onClick="@{()->vm.changednumber(5)}"
android:progress="@{vm.number}"
全部:
<?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="vm"
type="com.example.kotlinmutablelivedata.MyViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(vm.number)}"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+5"
android:onClick="@{()->vm.changednumber(5)}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<SeekBar
android:id="@+id/seekBar"
android:progress="@{vm.number}"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:max="15"
app:layout_constraintBottom_toTopOf="@+id/textone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
五 活动中启用:
java:
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
myViewModel =new ViewModelProvider(this).get(MyViewModel.class);
binding.setVm(myViewModel);
binding.setLifecycleOwner(this);
kotlin:
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
val binding: ActivityMainBinding =
DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.apply {
vm = viewModel //设定对象
lifecycleOwner = this@MainActivity //定义被观察者
}
文章来源