Android 自定义控件的双向绑定(DataBinding)和EditText的内部滚动

一个关于类似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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值