Android學習——Rxjava表單驗證

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章