前言
本篇將通過一個實際場景來學習RxBinding中的RxCompoundButton,J大神將Android中CompoundButton的一些事件及動作加以RxJava的觀察者模式并封裝了起來就形成了RxCompoundButton,使用起來也很簡單。
場景:注冊時需用戶點擊同意用戶協(xié)議選中框才可點擊注冊按鈕。
布局
布局中更需要一個注冊Button和一個用戶協(xié)議選中框CheckBox。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="15dp"
tools:context="com.leiholmes.rxbindingdemo.ui.RxCompoundButtonActivity">
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorGray"
android:text="注冊" />
<CheckBox
android:id="@+id/cb_contract"
android:layout_width="wrap_content"
android:layout_marginTop="10dp"
android:layout_height="wrap_content"
android:text="用戶協(xié)議" />
</LinearLayout>
Activity
View注入
使用ButterKnife獲取Button與CheckBox實例。
@BindView(R.id.btn_login)
Button btnLogin;
@BindView(R.id.cb_contract)
CheckBox cbContract;
checkedChanges選中狀態(tài)改變事件
RxCompoundButton.checkedChanges(CompoundButton view),內部封裝了OnCheckedChangeListener選中狀態(tài)改變監(jiān)聽。
//默認注冊按鈕不可點擊
btnLogin.setEnabled(false);
addDisposable(RxCompoundButton.checkedChanges(cbContract)
.subscribe(aBoolean -> {
RxView.enabled(btnLogin).accept(aBoolean);
btnLogin.setBackgroundResource(aBoolean ? R.color.colorPrimary : R.color.colorGray);
RxTextView.color(btnLogin).accept(aBoolean ? Color.parseColor("#ffffff") :
Color.parseColor("#000000"));
}));
addDisposable(RxView.clicks(btnLogin)
//防抖2s
.throttleFirst(2, TimeUnit.SECONDS)
.subscribe(o -> Toast.makeText(RxCompoundButtonActivity.this, "注冊成功",
Toast.LENGTH_SHORT).show()));
默認注冊按鈕不可點擊,當CheckBox被選中后則可點擊注冊,并修改注冊按鈕的樣式。
View操作
RxCompoundButton中也封裝了CompoundButton中例如setchecked()、toggle()等常用的操作,使用方式如下:
addDisposable(RxView.clicks(btnLogin)
.subscribe(o -> {
RxCompoundButton.checked(cbContract).accept(true);
RxCompoundButton.toggle(cbContract).accept(null);
}));
運行效果
最后看一下運行效果Gif。

運行效果
本文疑問
addDisposable()方法什么鬼?
飛機到本系列第一篇有講解:
RxBinding系列之RxView(一)
Lambda表達式什么鬼?
飛機到我寫的Lambda表達式教程:
Lambda表達式基本語法與應用
總結
通過實際場景來學習新知識掌握起來肯定比死啃理論快,建議碼友們都上手試試。
進階中的碼猿一枚,寫的不對的地方歡迎大神們留言指正,有什么疑惑或者建議也可以在我Github上RxBindingDemo項目Issues中提出,我會及時回復。
附上Demo的地址:
RxBindingDemo
另外:歡迎光臨我的Hexo個人博客:Lei’s Blog