How to databind to onTextChanged for an EditText on Android?

后端 未结 9 1191
悲哀的现实
悲哀的现实 2020-11-30 01:41

In Yigit Boyar and George Mount\'s talk on Android Databinding they illustrate how easy it is to bind to TextWatcher\'s onTextChanged (at 13:41). O

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 02:20

    The Easy Way

    If you are using onTextChange() to have updated text in model then you can directly use Two-way Binding.

    
        
    
    
    
    

    And you model class will have getter & setter.

    public class User {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    Now the Name in Model will be changed realtime with user interaction. So whenever use binding.getUser().getName(), you will get latest text.

    One-Way Binding will only gets updated when model value is changed. It does not update model back real time.

    android:text="@{user.name}"
    

    Two-Way Binding update model variable in real time with user input.

    android:text="@={user.name}"
    

    The ONLY difference is of = (equal sign) receives data changes to the property and listen to user updates at the same time.

提交回复
热议问题