RxBinding系列之RxCompoundButton(三)

441 阅读2分钟

前言

  本篇将通过一个实际场景来学习RxBinding中的RxCompoundButton,J大神将Android中CompoundButton的一些事件及动作加以RxJava的观察者模式并封装了起来就形成了RxCompoundButton,使用起来也很简单。
  
  场景:注册时需用户点击同意用户协议选中框才可点击注册按钮。

布局

  布局中更需要一个注册Button和一个用户协议选中框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="用户协议" />
</LinearLayout>

Activity

View注入

  使用ButterKnife获取Button与CheckBox实例。

@BindView(R.id.btn_login)
Button btnLogin;
@BindView(R.id.cb_contract)
CheckBox cbContract;

checkedChanges选中状态改变事件

  RxCompoundButton.checkedChanges(CompoundButton view),内部封装了OnCheckedChangeListener选中状态改变监听。

//默认注册按钮不可点击
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