android edittext remove focus after clicking a button

Put this in your button listener:

InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 

inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

EDIT

The solution above will break your app if no EditText is focused on. Modify your code like this:

add this method to you class:

public static void hideSoftKeyboard (Activity activity, View view) 
{
    InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
}

Then, in your button listener, call the method like this:

hideSoftKeyboard(MainActivity.this, v); // MainActivity is the name of the class and v is the View parameter used in the button listener method onClick.

I've successfully used the following in the onClick button code:

editText.setEnabled(false);
editText.setEnabled(true);

Somewhat less complex than other methods...


One workaround is to create a fake view to transfer focus to when you clearFocus in your edittext:

<EditText
        android:id="@+id/edt_thief"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:focusable="true"
        android:focusableInTouchMode="true"

Note that this view is invisible so it doesn't require any space in the layout.

In the control class, you can add a method like the following to trigger this focus transfer:

public void clearFocus(){
        yourEdittext.clearFocus();
        edtThief.requestFocus();
    }

You can then minimize the keyboard once edtThief has focus:

 public static void hideKeyboard(final View view) {
    InputMethodManager imm = (InputMethodManager) view.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}