Reputation: 486
When I edit one text field, I want another text field to change.
editTextCount.addTextChangedListener( new TextWatcher( ) {
@Override
public void afterTextChanged( Editable arg0 ) {
if ( arg0.length( ) == 0 ) {
return;
}
editTextAmount.setText( value
* Integer.parseInt( arg0.toString( ) )+"" );
}
@Override
public void beforeTextChanged( CharSequence arg0, int arg1, int arg2,
int arg3 ) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged( CharSequence arg0, int arg1, int arg2,
int arg3 ) {
// TODO Auto-generated method stub
}
} );
When I edit editTextCount, editTextAmount should change, but nothing happens.
Edit - Also, I forgot to mention this is in a custom ArrayAdapter. Could this be the problem?
Edit2 - I'm an idiot. I was declaring EditText editTextAmount
as a class level variable when I should have been declaring it final EditText editTextAmount
inside the getView() method. Thanks for all the help everyone. Your answers will help me with errors in the future.
Upvotes: 1
Views: 1433
Reputation: 2272
I am assuming that what you are trying to do is type a number into editTextCount
and that number will by multiplied by value
and write the final calculation to editTextAmount
. If this is the case, why not use,
editTextAmount.setText(value * Integer.parseInt(editTextCount.getText()));
It's really easy to use an Editable
object to create an inifinite recursion situation where you are calling afterTextChanged
infinitely, afterTextChanged
gets called if what it is listening on, or if its Editable
object gets changed. Thus if you change the Editable
object in afterTextChanged
it will call its self recursively.
It may be worth it to also try printing these values to identify any issues:
System.out.println("Value: " + value);
System.out.println("Count: " + Integer.parseInt(editTextCount.getText()));
System.out.println("Amount: " + (value * Integer.parseInt(editTextCount.getText())));
Upvotes: 2
Reputation: 152
afterTextChanged() should be fine. Are you sure, that some of the values are not initialized properly (e.g. value = 0)?
Upvotes: 1
Reputation: 5798
I think you need to implement your code in the onTextChanged()
instead of afterTextChanged()
. From the docs:
This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before.
On a side note, you should check for the input of parseInt before passing the value. It throws an exception in case of invalid number
Upvotes: 2