问题
Below is XML equivalent of what I'm trying to achieve, but without XML
<Button
android:id="@+id/bt_start"
android:onClick="@{() -> vm.onClickedStart()}"
android:text='@{vm.btStartLbl}' />
so if I have:
ConstraintLayout cl = findViewById(R.id.cl);
Button btn = new Button(MyActivity.this);
btn.setText("How to Data Bind here?");
btn.setOnClickListener(new OnClickListener (){ /* how to databind here? */ });
cl.addView(btn);
how to databind it as equivalent as xml above? is it possible?
回答1:
For automatic setting data, you could use ObservableField
Simplified version for auto-updating btn
:
ObservableField<String> title = new ObservableField<>();
Observable.OnPropertyChangedCallback propertyChangeCallback = new Observable.OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int property) {
btn.setText(title.get());
// here what you want to automatically update
}
};
public void onStart() {
// activity/fragment lifecycle method
title.addOnPropertyChangedCallback(propertyChangeCallback);
}
public void onStop() {
// activity/fragment lifecycle method
title.removeOnPropertyChangedCallback(propertyChangeCallback);
}
And then whenever you call title.set("some value");
, it will be automatically trigger the update.
来源:https://stackoverflow.com/questions/48386329/android-can-i-databinding-programatically-without-layout-xml