要检查2个EditTexts( accName 和 accMoney )是否为空,以便启用按钮( btnCrAcc )。
尝试像下面的代码一样。但它实际上并没有检查我想要的方式。当我更改accMoney字段时,它会检查两个EditTexts(但之后我可以将accName更改为“”,并且无论如何都会启用Button。
我认为一种可能的解决方案是为两个字段设置addTextChangedListener
,但它会消耗更多内存? (告诉我:这是一个不错的选择?)
如果有人告诉我如何正确地做到这一点,我真的很感激
我有这段代码:
protected void onCreate(Bundle savedInstanceState) {
//..
accName = (EditText) findViewById(R.id.txtName);
accMoney = (EditText) findViewById(R.id.txtMoney);
accDescr = (EditText) findViewById(R.id.txtDescr);
accsListView = (ListView) findViewById(R.id.listView);
//..
final Button btnCrAcc = (Button) findViewById(R.id.btnCreateAccount);
accMoney.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
btnCrAcc.setEnabled(!accName.getText().toString().trim().isEmpty());
btnCrAcc.setEnabled(!accMoney.getText().toString().trim().isEmpty()); // check this
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
答案 0 :(得分:1)
试试这个:
TextWatcher watcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
btnCrAcc.setEnabled(!accName.getText().toString().trim().isEmpty() && !accMoney.getText().toString().trim().isEmpty());
}
@Override
public void afterTextChanged(Editable editable) {
}
};
accMoney.addTextChangedListener(watcher);
accName.addTextChangedListener(watcher;
答案 1 :(得分:1)
创建一个implmenting TextWatcher的类:
private class MyTextWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// check for both edittexts if any of them is empty than disable the button
btnCrAcc.setEnabled(!accName.getText().toString().trim().isEmpty() && !accMoney.getText().toString().trim().isEmpty());
}
@Override
public void afterTextChanged(Editable editable) {
}
}
比使用textwatcher两个edittexts:
MyTextWatcher myTextWatcher = new MyTextWatcher();
accName.addTextChangedListener(myTextWatcher);
accMoney.addTextChangedListener(myTextWatcher);
答案 2 :(得分:0)
试试这个:
if(accName.getText().length() == 0 || accMoney.getText().length() == 0) {
//do your stuff
}
答案 3 :(得分:0)
您可以使用单个TextWatcher
实例:
TextWatcher myWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
btnCrAcc.setEnabled(!accName.getText().toString().trim().isEmpty() &&
!accMoney.getText().toString().trim().isEmpty());
}
});
accName.addTextChangedListener(myWatcher);
accMoney.addTextChangedListener(myWatcher);