RxJava2 处理简单表单验证大全看这一个就够了(监听按钮是否变色可点击)

1、处理表单验证

注:在build.gradle中添加依赖

implementation 'android.arch.persistence.room:rxjava2:1.1.1'
或者:
implementation 'com.jakewharton.rxbinding3:rxbinding-material:3.0.0-alpha2'

1.1、仅仅处理一个编辑框以及按钮变色和可点击

可以使用RXTextView
 private fun initView() {
        RxTextView.textChanges(yaoqingCode!!).map { it ->//参数放的是控件id
            it.length == 6//输入框的限定
        }.subscribe {
            registe.isEnabled = it//按钮是否可被点击
        }
    }

1.2、仅仅处理两个参数

 Observable.combineLatest(RxTextView.textChanges(mPhone), RxTextView.textChanges(mPsw),
                new BiFunction<CharSequence, CharSequence, Boolean>() {
                    @Override
                    public Boolean apply(CharSequence charSequence, CharSequence charSequence2) throws Exception {
                        return charSequence.length() == 11 && charSequence2.length() > 5;//限定
                    }
                }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                mLogin.setEnabled(aBoolean);//按钮
            }
        });

1.3、处理两个以上参数

Observable.combineLatest(RxTextView.textChanges(etPhone), RxTextView.textChanges(password)
                , RxTextView.textChanges(etCode), Function3<CharSequence, CharSequence, CharSequence, Boolean> { t1, t2, t3 ->
            t1.length == 11 && t2.length > 5 && t3.length > 3//限定
        }).subscribe { aBoolean ->
            tvLogin.isEnabled = aBoolean//按钮
        }

1.4、在 Activity/Fragment 销毁生命周期中取消异步操作防止内存泄露

private val mDisposables = CompositeDisposable()


private fun initView() {

        val subscribe = Observable.combineLatest(RxTextView.textChanges(etPhone), RxTextView.textChanges(password)
                , RxTextView.textChanges(etCode), Function3<CharSequence, CharSequence, CharSequence, Boolean> { t1, t2, t3 ->
            t1.length == 11 && t2.length > 5 && t3.length > 3
        }).subscribe { aBoolean ->
            tvLogin.isEnabled = aBoolean
        }
        mDisposables.add(subscribe)

        
    }

//回收
override fun onDestroy() {
        super.onDestroy()
        if (!mDisposables.isDisposed) {
            mDisposables.dispose()
        }
        mDisposables.clear()
    }

推荐很好的文章:

https://www.jianshu.com/p/b672724dbff8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值