Android databinding 踩坑记录

在使用@BindingAdapter注解的时候,第一个属性的子类也会触发注解的方法,所以在定义多个value的时候,如果设置了requireAll = false,那么这个方法会和其他的定义了相同value并且使用同一种类型或者子类的方法冲突,会导致databinding找不到正确的方法在执行,例如:

@BindingAdapter(value = {"android:text", "my_price_span_custome", "span_text_size"}, requireAll = false)
    public static void setTextSpan(TextView textView, String text, boolean span, int textSize) {
        if (!TextUtils.isEmpty(text)) {
            if (span && !text.equals("¥0")) {
                SpannableString sbs = new SpannableString(text);
                if (text.length() >= 5) {
                    sbs.setSpan(new AbsoluteSizeSpan(textSize, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    sbs.setSpan(new AbsoluteSizeSpan(textSize, true), text.length() - 3, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    textView.setText(sbs);
                }
            } else {
                textView.setText(text);
            }
        }
    }

//EditTextView双向绑定
    @BindingAdapter("android:text")
    public static void setEditText(EditText editText, String text) {
        if (!editText.getText().toString().equals(text)) {
            editText.setText(text);
        }
    }
//EditTextView双向绑定
    @InverseBindingAdapter(attribute = "android:text", event = "edit_textview_change")
    public static String setEditTextChange(EditText editText) {
        return editText.getText().toString();
    }

    //EditTextView双向绑定
    @BindingAdapter(value = "edit_textview_change", requireAll = false)
    public static void setOnEditTextViewChangeListner(EditText editText, InverseBindingListener bindingListener) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                bindingListener.onChange();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                bindingListener.onChange();
            }

            @Override
            public void afterTextChanged(Editable s) {
                bindingListener.onChange();
            }
        });
    }

因为定义了相同的"android:text",这样会导致setEditText方法不会被执行,databinding的实现类会执行setTextSpan方法,导致onChange无限回调。只需要把requireAll设置为true就行了,true表示所有定义的value都被设置了属性,该方法才会被执行。

你可能感兴趣的:(Android databinding 踩坑记录)