Create two-way binding with Android Data Binding

前端 未结 6 1329
情深已故
情深已故 2020-12-08 06:33

I have implemented the new Android data-binding, and after implementing realised that it does not support two-way binding. I have tried to solve this manually but I am strug

6条回答
  •  隐瞒了意图╮
    2020-12-08 06:47

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

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

    with:

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

    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.

    (PREVIOUS ANSWER):

    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);
    }}
    

    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);
    }
    

    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

提交回复
热议问题