make editText lose focus on back press

2019-01-24 00:48发布

问题:

In my activity, I have a editText field. When the user taps on it, the editText gains the focus and the keyboard appears. Now, when the user presses the hardware back button on the phone, the keyboard disappears but the cursor remains in the Edittext, i. e., it still has the focus. Is it possible to make the EditText lose focus when back button is pressed? I tried using the following code but it didn't work:

@Override
public void onBackPressed() {
    vibrator.vibrate(Constants.DEFAULT_VIBRATE_TIME);
    myEditText.clearFocus();
            super.onBackPressed();
}

回答1:

Just extend EditText:

public class EditTextV2 extends EditText
{
    public EditTextV2( Context context )
    {
        super( context );
    }

    public EditTextV2( Context context, AttributeSet attribute_set )
    {
        super( context, attribute_set );
    }

    public EditTextV2( Context context, AttributeSet attribute_set, int def_style_attribute )
    {
        super( context, attribute_set, def_style_attribute );
    }

    @Override
    public boolean onKeyPreIme( int key_code, KeyEvent event )
    {
        if ( event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP )
            this.clearFocus();

        return super.onKeyPreIme( key_code, event );
    }
}

And in the xml just use <yourPackage.EditTextV2> instead of <EditText>.

Note: You may need to add/remove constructors to this class depending on the min API you're supporting. I suggest just adding them all and removing the ones whose super() calls get underlined in red.



回答2:

You can make another of your Views focusable, for example an ImageView. Be sure to make it focusable in touch mode, using setFocusableInTouchMode(true) and on onResume() make that View to requestFocus().

Also you can create a dummy View with 0 dimensions and perform same steps described above.

I hope this helps.



回答3:

Add view like the following higher than your EditText:

<LinearLayout
    android:layout_width="0px"
    android:layout_height="0px"
    android:focusable="true"
    android:focusableInTouchMode="true" />

Also to hide keyboard add this in onBackPressed():

((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(myEditText.getWindowToken(), 0);


回答4:

This may be a possible solution:

EditText et;
et.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if(i == KeyEvent.KEYCODE_BACK) {
                et.clearFocus();
                return true;
            }
            else return false;
        }
    });