在gradle中添加dataBinding,开启数据绑定。
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.moyu.databinding"
minSdkVersion 28
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
dataBinding {
enabled true
}
}
public class MainActivity extends AppCompatActivity {
MyViewModel myViewModel;
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
myViewModel = new ViewModelProvider(this).get(MyViewModel.class);
myViewModel.getNumber().observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer integer) {
binding.textView.setText(String.valueOf(integer));
}
});
binding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myViewModel.add();
}
});
}
}
使用数据绑定
ActivityMainBinding binding;
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
取代了
setContentView(R.layout.activity_main);
android:onClick="@{()->data.add()}"
取代了
// binding.button.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// myViewModel.add();
// }
// });
binding.setData(myViewModel);
binding.setLifecycleOwner(this);
取代了
//观察者
// myViewModel.getNumber().observe(this, new Observer<Integer>() {
// @Override
// public void onChanged(Integer integer) {
// binding.textView.setText(String.valueOf(integer));
// }
// });