在使用@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都被設置了屬性,該方法才會被執行。