用户注册登录等表单校验场景下,只有账号和密码内容都不为空的情况下,按钮才可点击并实现按钮背景变化。
// rxbinding3 内部已添加rxjava依赖
implementation "com.jakewharton.rxbinding3:rxbinding:3.0.0"
combineLatest 操作符用来将多个Observable发射的数据组装起来然后在发射. 通过Func类来组装多个Observable发射的数据, 等到最后一个Observable发射数据了, 然后把所有发射的数据交给Fun进行组合, 然后把组合后的数据发射出去.
话不多说,直接上代码:
// 1.继承TextWatcher
class EditTextMonitor(private val mPublishSubject: PublishSubject<String>) : TextWatcher {
override fun beforeTextChanged(
s: CharSequence,
start: Int,
count: Int,
after: Int
) {
}
override fun onTextChanged(
s: CharSequence,
start: Int,
before: Int,
count: Int
) {
}
override fun afterTextChanged(s: Editable) {
mPublishSubject.onNext(s.toString())
}
}
// 处理登陆按钮是否可点击
val mAccountSubject = PublishSubject.create<String>()
val mPasswordSubject = PublishSubject.create<String>()
// etAccount etPwd 账号和密码输入框
etAccount.addTextChangedListener(EditTextMonitor(mAccountSubject))
etPwd.addTextChangedListener(EditTextMonitor(mPasswordSubject))
Observable.combineLatest(mAccountSubject, mPasswordSubject,
BiFunction {
name: String, password: String ->
val nameLen = name.length
val passwordLen = password.length
nameLen > 0 && passwordLen > 0
}
).subscribe {
clickFlag: Boolean ->
// 满足以上nameLen > 0 && passwordLen > 0后
if (clickFlag) {
// btnLogin 登录按钮
btnLogin.apply {
isEnabled = true
setBackgroundResource(R.color.white)
setTextColor(Color.BLACK)
}
// 不满足:
} else {
btnLogin.apply {
isEnabled = false
setBackgroundResource(R.color.white_cc)
setTextColor(Color.WHITE)
}
}
}
(Java环境为1.8 支持lamda表达式)
public class EditTextMonitor implements TextWatcher {
private PublishSubject<String> mPublishSubject;
public EditTextMonitor(PublishSubject<String> publishSubject) {
mPublishSubject = publishSubject;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
mPublishSubject.onNext(s.toString());
}
}
// 处理登陆按钮是否可点击
PublishSubject<String> mAccountSubject = PublishSubject.create();
PublishSubject<String> mPasswordSubject = PublishSubject.create();
edLoginAccount.addTextChangedListener(new EditTextMonitor(mAccountSubject));
edLoginPwd.addTextChangedListener(new EditTextMonitor(mPasswordSubject));
Observable.combineLatest(mAccountSubject, mPasswordSubject, (name, password) -> {
int nameLen = name.length();
int passwordLen = password.length();
return nameLen > 0 && passwordLen > 0;
}).subscribe(clickFlag -> {
if (clickFlag) {
btnLogin.setEnabled(true);
} else {
btnLogin.setEnabled(false);
}
});