您的位置:首页 > 移动开发 > Android开发

Android:EditText动态输入监听TextWatcher

2016-08-09 16:07 387 查看
我们经常看到类似于必须等到姓名,密码都输入有内容,登录按钮才会可点击的功能

代码实现就是用到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键这类按键.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息