简体   繁体   中英

Android EditText change other EditText value

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.

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

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())));

afterTextChanged() should be fine. Are you sure, that some of the values are not initialized properly (eg value = 0)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM