我们经常看到类似于必须等到姓名,密码都输入有内容,登录按钮才会可点击的功能
代码实现就是用到TextWatcher
下面我们监听两个 EditText etLoginname,etLoginpwd;
的动态输入,当两个EditText都有内容的时候Button btLogin;
可点击
代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//etLoginname= findViewById();
//etLoginpwd= findViewById();
//btLogin=findViewById();
etLoginname.addTextChangedListener(new MyTextWatcher());
etLoginpwd.addTextChangedListener(new MyTextWatcher());
}
private class MyTextWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
ALog.i("keychange", "before");
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ALog.i("keychange", "on");
if (!TextUtils.isEmpty(etLoginname.getText().toString()) && !TextUtils.isEmpty(etLoginpwd.getText().toString())) {
btLogin.setBackgroundResource(R.color.white);
btLogin.setEnabled(true);
} else {
btLogin.setBackgroundResource(R.color.gray);
btLogin.setEnabled(false);
}
}
@Override
public void afterTextChanged(Editable s) {
ALog.i("keychange", "after");
}
}
有些人会用setOnKeyListener()这个方法,但是看api可以发现
这个方法:
* Register a callback to be invoked when a hardware key is pressed in this view.
* Key presses in software input methods will generally not trigger the methods of
* this listener.
* @param l the key listener to attach to this view
是用于硬件的key,适用于以前非触屏式手机,现在只相应类似与全触屏输入法Enter键这类按键.