Search code examples
javaandroideclipsefocusandroid-edittext

Clear edittext focus and hide keyboard when button is pressed


I'm making an app with edittext and a button. When I enter something into edittext and then click a button, I want the keyboard and focus on edittext to disappear but I can't seem to do it.

I inserted these 2 lines of code in XML:

android:focusable="true"
android:focusableInTouchMode="true"

I also tried to add this in the button click method:

edittext.clearFocus();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

And it just won't work, after I press the button, the keyboard remains there and edittext still has focus.


Solution

  • another solution is, create a dummy layout

    <!-- Dummy item for focus at startup -->
    <LinearLayout
        android:id="@+id/dummy_id"
        android:orientation="vertical"
        android:layout_width="0px"
        android:layout_height="0px"
        android:focusable="true"
        android:focusableInTouchMode="true" />
    

    and set the focus in your onButtonClickFunction

    ((LinearLayout) findViewById(R.id.dummy_id)).requestFocus();