2

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?

7
  • 4
    "how to databind it as equivalent as xml above?" -- btn.setOnClickListener(() -> vm.onClickedStart()); This assumes that you have a vm in scope that has an onClickedStart() method. IOW, you do not "databind programmatically", but rather simply program. Commented Jan 22, 2018 at 16:42
  • Thanks, let me try - how about: android:text='@{vm.btStartLbl}' how to bind it from Java? Commented Jan 22, 2018 at 16:45
  • Call setText(vm.getBtStartLbl()) (modifying that method name to match the actual one, as there are a few possibilities). Commented Jan 22, 2018 at 16:49
  • I'm not sure if vm.getBtStartLbl() will update my text if variable changed, e.g: vm.label=oldVal; and getBtStartLbl(){ return this.label; } if vm.label = newVal will my button text get updated to newVal? Commented Jan 22, 2018 at 16:58
  • No. You would need to call setText() again. Commented Jan 22, 2018 at 17:12

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Let me try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.