android databinding优雅处理快速点击

使用到的库:

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以上。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,990评论 25 709
  • 先吐槽下,不说不爽,不说不通达 不吐不快,集合我这几天学习 DataBinding 的经历说几句。DataBind...
    前行的乌龟阅读 21,346评论 13 46
  • 原文链接:https://github.com/opendigg/awesome-github-android-u...
    IM魂影阅读 33,066评论 6 472
  • 把杜拉拉升职记粘贴入微信文档,每天一篇翻译,既可以提醒自己不要笨,也做事情了。但这些都是下班或者领导不在时候做的。...
    粉黛小姐阅读 1,072评论 0 0
  • “我意识到自己所有的身心都沉浸在那阵风里,所有的生活都聚集在此处、此时。世上无一涣散的不安。” 下半年我无所事事 ...
    水槛阅读 2,224评论 2 4

友情链接更多精彩内容