OnKeyListener problem enabling a button
Thanks in advance for your answers. I am working on a basic tax calculator to help me better understand the fundamentals to the Android SDK. The user enters a subtotal and a tax rate (.08) a开发者_运维知识库nd they press calculate to calculate the solution. I disable the calculate button until both fields have contents. My problem is that when the user enters numbers for both of the fields, the calculate button is still disabled. I posted the code I currently am running (the OnKeyListener). The edittext fields are registered to the listener.
private OnKeyListener mKeyListener = new OnKeyListener()
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
switch(v.getId())
{
case R.id.txtSub:
cmdSubmit.setEnabled(txtTax.getText().length()>0
&& txtSub.getText().length() > 0);
break;
case R.id.txtTax:
cmdSubmit.setEnabled(txtTax.getText().length()>0
&& txtSub.getText().length() > 0);
break;
}
return false;
}
};
If you look at the spec for OnKeyListener you'll notice that it gets invoked BEFORE the KeyEvent is given to the view. Other than that this looks right: I would suspect you aren't binding the listener to the right view. Put a break point in the method and make sure it is getting invoked correctly.
I've personally found the TextWatcher
s a much nicer way of keeping track of whether an EditText
has data or not:
TextWatcher tw = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
cmdSubmit.setEnabled(!Utils.isStringBlank(txtTax.getText().toString()) &&
!Utils.isStringBlank(txtSub.getText().toString()));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
};
txtTax.addTextChangedListener(tw);
txtSub.addTextChangedListener(tw);
精彩评论