6

An android.widget.EditText can get focus by 2 reasons as I know:

Case 1. End-users touch on the edit text by purpose.

Case 2. The system give the Edit Text automatically.

  • Navigation
  • First default focus
  • ...

My question is: How to I detect Case 2 ONLY? ( Event listener?)

The reason I want to detect case 2 is: I want to set current position is the last position IF the edit text get focus by Case 2.

EditText.setOnFocusChangeListener is for both case1, case2 so It seems that I can't use this.

Thank you!

LHA
  • 9,398
  • 8
  • 46
  • 85

1 Answers1

10

Updated
Implement android.view.View.OnFocusChangeListener in your activity (for example) and set yourView.setOnFocusChangeListener(yourActivity)
If you combine it with OnTouchListener then you can filter out user touches since onTouch() is called first - you may set boolean class member. Make sure to reset that boolean when focus is lost.

The code should be somewhat like this:

...
import android.view.View.OnFocusChangeListener;

...

public class MainActivity extends Activity implements OnFocusChangeListener, OnTouchListener {

    boolean userTouchedView;

    @Override
    public View onCreateView(...) {
        ...
        yourView.setOnFocusChangeListener(this);
        ...
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus && !userTouchedView)) {
            //YOUR CASE 2
        }
        else if(!hasFocus)
            userTouchedView=false;
    }

    @Override
    public boolean onTouch(final View v, MotionEvent event) {
        if(v==yourView){
            userTouchedView=true;
        }
    }

}
LHA
  • 9,398
  • 8
  • 46
  • 85
sberezin
  • 3,266
  • 23
  • 28