Android的Data Binding允许我们在View层和Model层之间建立双向绑定关系。本文介绍如何使用float MutableLiveData完成双向数据绑定。
首先,在build.gradle文件中添加以下依赖:
android {
...
dataBinding {
enabled = true
}
}
dependencies {
...
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
}
在xml布局文件中使用Data Binding控件,同时设置data和viewModel的对象。
接下来,在ViewModel中定义一个MutableLiveData对象,并且在onTextChanged方法中更新floatValue的值。
public class MyViewModel extends ViewModel {
public MutableLiveData floatValue = new MutableLiveData<>();
public void onTextChanged(CharSequence s) {
try {
floatValue.setValue(Float.parseFloat(s.toString()));
} catch (NumberFormatException e) {
floatValue.setValue(null);
}
}
}
添加@Bindable注解,然后在getFloatValue()和setFloatValue()中调用该方法,这是实现双向绑定的关键。
public class MyViewModel extends BaseObservable {
private Float floatValue;
@Bindable
public Float getFloatValue() {
return floatValue;
}
public void setFloatValue(Float floatValue) {
this.floatValue = floatValue;
notifyPropertyChanged(BR.floatValue);
}
public void onTextChanged(CharSequence s) {
try {
setFloatValue(Float.parseFloat(s.toString()));
} catch (NumberFormatException e) {
setFloatValue(null);
}
}
}
最后,在Activity中设置DataBinding,并绑定ViewModel。
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
MyViewModel viewModel = new MyViewModel();
binding.setViewModel(viewModel);
binding.executePendingBindings();