How to databind to onTextChanged for an EditText on Android?

后端 未结 9 1176
悲哀的现实
悲哀的现实 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:06

    the best way for this is adding bind adapter and a text watcher.

    public class Model{
        private TextWatcher textWatcher;
    
    public Model(){
            this.textWatcher= getTextWatcherIns();
    }
    
    private TextWatcher getTextWatcherIns() {
            return new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    //do some thing
                }
    
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    //do some thing
    
                }
    
                @Override
                public void afterTextChanged(Editable s) {
                    //do some thing
                }
            };
        }
    
        public TextWatcher getTextWatcher() {
            return textWatcher;
        }
    
        public void setTextWatcher(TextWatcher textWatcher) {
            this.textWatcher = textWatcher;
        }
    
        @BindingAdapter("textChangedListener")
        public static void bindTextWatcher(EditText editText, TextWatcher textWatcher) {
            editText.addTextChangedListener(textWatcher);
        }
    }
    

    and in your xml add this attr to your edit text

    
    

提交回复
热议问题