Android: ViewModel+LiveData+Data
2023-06-20 本文已影响0人
程序狮
EditText实现双向绑定
配置: 模块build中设置使用DataBinding
defaultConfig {
...
dataBinding{
enabled true
}
}
Activity
//设置contentView 返回值是ViewBinding对象
ALoginBinding dataBinding = DataBindingUtil.setContentView(this, R.layout.a_login);
EmergencyContactViewModel viewModel = new ViewModelProvider(this).get(EmergencyContactViewModel.class);
dataBinding.setViewModel(viewModel);
dataBinding.setLifecycleOwner(this);
dataBinding.setViewModel(viewModel);
dataBinding.setLifecycleOwner(this);
注意此处要记得databinding和Viewmodel进行绑定
然后来到我们需要支持Databinding的xml布局文件中
将光标定位在 最开始
然后按下Alt+Enter键
可快捷生成DataBinding代码
<?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:etApp="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.ceshi.LoginViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/et_phoneNumber"
android:layout_width="match_parent"
android:layout_height="42dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:inputType="phone"
android:afterTextChanged="@{(editable) -> viewModel.setPhoneNumber(editable.toString())}"
android:text="@{viewModel.phoneNumber}"
android:textSize="15sp"
android:textColor="@color/title_333" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
主要是这两句
android:afterTextChanged="@{(editable) -> viewModel.setPhoneNumber(editable.toString())}"
android:text="@{viewModel.phoneNumber}"
ViewModel类
public class LoginViewModel extends ViewModel {
private MutableLiveData<String> phoneNumber;
public LoginViewModel() {
phoneNumber = new MutableLiveData<>();
}
public void setPhoneNumber(String phoneNumber1) {
this.phoneNumber.setValue(phoneNumber1);
}
}