Android: hide keyboard when touch inside a customized Dialog


Ask by : Vigor November 05, 2012 08:42

I have a customized Dialog. Inside the dialog, there's an EditText. When I touch inside the EditText, the soft keyboard is shown. I want to hide this keyboard when I touch inside the other place of the Dialog.

I know how to hide a keyboard in activity. I just don't know how to do this in Dialog.

Thank you.

View original question

Answer by : GreezerNovember 05, 2012 08:42

You can do that easy by using focuslisners, see my code sample below:

EditText.setOnFocusChangeListener(new View.OnFocusChangeListener() 
        { 
            @Override 
            public void onFocusChange(View v, boolean hasFocus) 
            { 
                if (hasFocus) 
                { 
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
                    imm.showSoftInput(EditText, InputMethodManager.SHOW_IMPLICIT); 
                }
                else
                {
                   InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                   imm.hideSoftInputFromWindow(EditText.getWindowToken(), 0);
                }
            } 
        });

edit:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <LinearLayout
            android:id="@+id/wrapper"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:focusable = "true"
            android:isFocusableInTouchMode = "true"
            android:clickable = "true" > 

                <EditText
                android:id="@+id/EditText"
                android:layout_width="fill_parent"
                android:layout_height="50dp"
                android:hint="hint"
                android:singleLine="true" />

            </LinearLayout>         
    </RelativeLayout>

\to be sure to get focus:

    LinearLayout actionHide = (LinearLayout) findViewById(R.id.wrapper);
        actionHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                actionHide.requestFocus(); // use this to trigger the focus listner
                //or use code below to set the keyboard to hidden
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(EditText.getWindowToken(), 0);

            }
        });
View original answer