Android-Data Binding

android databinding优雅处理快速点击

2018-03-08  本文已影响61人  chenzhenlindx

使用到的库:

1. 引入RxBinding
compile 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
2. 开启dataBinding支持
dataBinding {
        enabled = true
}
3. 创建BindingAdapter方法

在这里,通过throttleFirst方法,实现了去抖动的处理。

    @BindingAdapter("android:onClick")
    public static void onClick(final View view, final View.OnClickListener listener) {
        RxView.clicks(view)
                //两秒钟之内只取一个点击事件,防抖操作
                .throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        listener.onClick(view);
                    }
                });
    }
4. xml引用android:onClick="@{()->callBack.click()}"
<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>
        <variable
            name="callBack"
            type="cn.czl.databindingclick.MainActivity" />
    </data>

    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="cn.czl.databindingclick.MainActivity">

        <TextView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:gravity="center"
            android:onClick="@{()->callBack.click()}"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>
</layout>
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        binding.setCallBack(this);
    }

    public void click() {
        Log.d(TAG, "click: ");
    }
}

运行,查看日志


image.png

可以看到,日志打印时间间隔2s以上。

上一篇下一篇

猜你喜欢

热点阅读