Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect EditText got focus by Android. Not by end-user touching on the edit text?

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!

like image 572
Loc Avatar asked Nov 07 '14 22:11

Loc


1 Answers

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;
        }
    }

}
like image 55
sberezin Avatar answered Sep 29 '22 18:09

sberezin