Android - Can I Databinding programatically? - without layout XML

大憨熊 提交于 2020-02-25 04:47:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!