一个关于类似TextInputLayout的功能的自定义控件进行双向绑定
用法:
什么是BindingAdapter?
BindingAdapter用来设置布局中View的自定义属性,当使用该属性时,可以自定义其行为。
1、作用于方法
2、它定义了xml的属性赋值的java实现
3、方法必须为公共静(public static)方法,可以有一到多个参数。
@BindingAdapter("app:text")
public static void setText(TitleWithHintTextInputLayout customTextInputLayout, String text) {
customTextInputLayout.setText(text);
}
什么是InverseBindingAdapter?
InverseBindingAdapter用于关联某个用于接收View变更的方法,典型的例子EditText.TextWatcher接收输入字符的变更。这与BindingAdapters有一定的相似性:
@InverseBindingAdapter(attribute = "app:text", event = "app:textAttrChanged")
public static String getText(CustomTextInputLayout customTextInputLayout) {
return customTextInputLayout.getText();
}
事件的默认值是带有AttrChanged的属性名称。在上面的例子中,默认值是android:textAttrChanged,即使它没有提供。
事件属性用于通知数据绑定系统值已更改。开发人员通常会创建一个BindingAdapter来分配事件。比如:
@BindingAdapter(value = "app:textAttrChanged", requireAll = false)
public static void setListener(CustomTextInputLayout customTextInputLayout, final InverseBindingListener listener) {
if (listener != null) {
SimpleTextWatcher newTextWatch = new SimpleTextWatcher() {
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
listener.onChange();
}
};
SimpleTextWatcher oldTextWatch = ListenerUtil.trackListener(customTextInputLayout, newTextWatch, R.id.textWatcher);
if (oldTextWatch != null) {
customTextInputLayout.removeTextWatch(oldTextWatch);
}
customTextInputLayout.addTextWatch(newTextWatch);
}
}
完整代码:
public class CustomTextInputLayout extends RelativeLayout {
private AppCompatTextView tvHint;
private Mul