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()
}
推荐很好的文章: