且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Android 数据绑定创建双向绑定

更新时间:2021-10-31 09:03:01

EDIT 04.05.16:Android 数据绑定现在自动支持两种方式绑定!只需替换:

EDIT 04.05.16: Android Data binding now supports two way-binding automatically! Simply replace:

android:text="@{viewModel.address}"

与:

android:text="@={viewModel.address}"

例如在 EditText 中,您将获得双向绑定.确保您更新到最新版本的 Android Studio/gradle/build-tools 以启用此功能.

in an EditText for instance and you get two-way binding. Make sure you update to the latest version of Android Studio/gradle/build-tools to enable this.

(以前的回答):

我尝试了 Bhavdip Pathar 的解决方案,但这未能更新我绑定到同一变量的其他视图.我通过创建自己的 EditText 以不同的方式解决了这个问题:

I tried Bhavdip Pathar's solution, but this failed to update other views I had bound to the same variable. I solved this a different way, by creating my own EditText:

public class BindableEditText extends EditText{

public BindableEditText(Context context) {
    super(context);
}

public BindableEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public BindableEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

private boolean isInititalized = false;

@Override
public void setText(CharSequence text, BufferType type) {
    //Initialization
    if(!isInititalized){
        super.setText(text, type);
        if(type == BufferType.EDITABLE){
            isInititalized = true;
        }
        return;
    }

    //No change
    if(TextUtils.equals(getText(), text)){
        return;
    }

    //Change
    int prevCaretPosition = getSelectionEnd();
    super.setText(text, type);
    setSelection(prevCaretPosition);
}}

使用此解决方案,您可以随心所欲地更新模型(TextWatcher、OnTextChangedListener 等),它会为您处理无限更新循环.使用此解决方案,模型设置器可以简单地实现为:

With this solution you can update the model any way you want (TextWatcher, OnTextChangedListener etc), and it takes care of the infinite update loop for you. With this solution the model-setter can be implemented simply as:

public void setFirstName(String firstName) {
    this.firstName = firstName;
    notifyPropertyChanged(BR.firstName);
}

这会在模型类中放置更少的代码(您可以将侦听器保留在您的 Fragment 中).

This puts less code in the model-class (you can keep the listeners in your Fragment).

如果您对我的问题有任何意见、改进或其他/更好的解决方案,我将不胜感激

I would appreciate any comments, improvements or other/better solutions to my problem