Clear Focus of EditText Android

I have an Activity with an EditText and a list of data below it. I use EditText as search tool to filter the list. When the User clicks on the EditText, the keyboard is shown and he can type in some Text – fine. But when the user clicks outside EditText, I want the EditText to be no more in focus i.e. the keyboard hides until the user clicks again on the EditText.

Some code below need to add to your activity or if you use fragment add it in your parent activity.

@Override    public boolean dispatchTouchEvent(MotionEvent event) {        if (event.getAction() == MotionEvent.ACTION_DOWN) {            View v = getCurrentFocus();            if ( v instanceof EditText) {                Rect outRect = new Rect();                v.getGlobalVisibleRect(outRect);                if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {                    v.clearFocus();                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);                }            }        }        return super.dispatchTouchEvent( event );    }

Others issue when running activity the first time, EditText immediately gaining focus. If you want to remove focus of EditText, just do some simple trick below:

<!-- Dummy item to prevent AutoCompleteTextView from receiving focus --><LinearLayout    android:focusable="true"     android:focusableInTouchMode="true"    android:layout_width="0px"     android:layout_height="0px"/>
<!-- :nextFocusUp and :nextFocusLeft have been set to the id of this componentto prevent the dummy from receiving focus again --><AutoCompleteTextView android:id="@+id/autotext"    android:layout_width="fill_parent"     android:layout_height="wrap_content"    android:nextFocusUp="@id/autotext"     android:nextFocusLeft="@id/autotext"/>


See also  Converting dp into pixel Android

About wahyuway

Check Also

Cannot Launch Android Emulator

Android Emulator is useful when you want to debug locally inside your environment. We can …

Leave a Reply