0

I added an OnFocusChangeListener to my EditText so that I can do some validation on the value when the user clicks outside, or tabs out of, the EditText view:

  EditText myEditText = (EditText) itemView.findViewById(R.id.myedittext);
  myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
  @Override
  public void onFocusChange(View view, boolean hasFocus) {
    EditText editText = (EditText)view;
    if (!hasFocus) {
      validate(editText.getText().toString());
    }
  }
}

However, it appears the onFocusChange() method is being called like a textChanged() method. It's getting called every time I enter anything into the text field. I tried this on both a 2.2 simulator and my own hardware device and they act the same.

I would appreciate any insight on how the OnFocusChangeListener should work and why it's working the way it is for me.

Thank you in advance.

NLam
  • 537
  • 1
  • 11
  • 25

2 Answers2

1

First, you shouldn't have to redeclare the EditText editText in the onFocusChange method. myEditText should be a class variable that is set in the onCreate method. I think your code is treating it a two separate instances.

And try adding the OnEditorActionListener

myEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            validate(myEditText.getText().toString());
            return true;
        }
        return false;
    }
});
Woodsy
  • 3,177
  • 2
  • 26
  • 50
0

I also encountered the problem and found no detail information about handling onFocusChange() together with EditText text changed.

I'm sure onFocusChange() get called every time [editText].setText() is being called. In my case I want to validate the input text after the input is done or hasFocus() returns false. That validation is followed by setting the text agian. So these 2 processes onFocusChange() and [editText].setText() are interrupting each other.

Solution Knowing when Edit text is done being edited

By using something like this

 meditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {

                yourcalc();

                return true;
            }
            return false;
        }
    });
Community
  • 1
  • 1
johnkarka
  • 365
  • 2
  • 14