项目里面刚开始使用RX系列开源库,以及逐步替换网络请求为Retrofit+OKHttp组合,再不换就OUT了,啥也不说了,先导入所有要用的包:
//retrofit
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
//rx+retrofit
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
//rxjava
compile "io.reactivex.rxjava2:rxjava:2.0.8"
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
//rxbinding
compile 'com.jakewharton.rxbinding2:rxbinding:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-support-v4:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-design:2.0.0'
compile 'com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:2.0.0'
app项目里面注册,登录,找回密码,认证等等页面不要太多,通常做法都是要对各个输入框进行监听的,那以前也一直用TextWatcher,现在大热的RX系列已然凭借各种优势要把前浪拍在沙滩上了,说起优势嘛其实就是方便,简洁,明了,简单情况下也许体现不出太多来,但是一旦需求情况复杂的时候这三个优势就特别明显了。直接上项目里面的例子,注册页面,有6个输入框,一个checkbox,一个按钮,要求输入框都有值得时候且checkbok为true,按钮由灰变红,才可以点击。
private void inputObserver(){
Observable<CharSequence> observablePhone = RxTextView.textChanges(register_phone);
Observable<CharSequence> observableCode = RxTextView.textChanges(register_code);
Observable<CharSequence> observablePassword = RxTextView.textChanges(register_password);
Observable<CharSequence> observablePasswordAgain = RxTextView.textChanges(register_password_again);
Observable<CharSequence> observableCompany = RxTextView.textChanges(register_company);
Observable<CharSequence> observableContact = RxTextView.textChanges(register_contact);
Observable.combineLatest(observablePhone, observableCode, observablePassword, observablePasswordAgain, observableCompany, observableContact
, new Function6<CharSequence, CharSequence, CharSequence, CharSequence, CharSequence, CharSequence, Boolean>() {
@Override
public Boolean apply(@io.reactivex.annotations.NonNull CharSequence phone
, @io.reactivex.annotations.NonNull CharSequence code
, @io.reactivex.annotations.NonNull CharSequence password
, @io.reactivex.annotations.NonNull CharSequence passwordAgain
, @io.reactivex.annotations.NonNull CharSequence company
, @io.reactivex.annotations.NonNull CharSequence contact) throws Exception {
return StringUtil.valid(phone.toString())&&StringUtil.valid(code.toString())
&&StringUtil.valid(password.toString()) &&StringUtil.valid(passwordAgain.toString())
&&StringUtil.valid(company.toString())&&StringUtil.valid(contact.toString())
&®ister_check.isChecked();
}
}).subscribe(new Consumer<Boolean>() {
@Override
public void accept(@io.reactivex.annotations.NonNull Boolean aBoolean) throws Exception {
isBtnEnable=aBoolean;
LogApi.DebugLog("observable===","=================="+isBtnEnable);
if (aBoolean){
bt_register.setBackgroundResource(R.drawable.btn_red_solid_bg);
}else {
bt_register.setBackgroundResource(R.drawable.btn_gray_solid_bg);
}
}
});
}
通过RxTextView里面textChanges方法对每个EditText的监听,通过Observable里面的combineLatest方法将六个输入框的值汇总过来,我们在该方法里面判断每个输入框里面的字符串是否为空,最后加上checkbox的判断,就可以来得到是否按钮能够点击了。最后subscribe订阅观察者,在观察者里面修改按钮的颜色,当然也可以记录下来bool值,以便后面判断。