Android:在自定义对话框内触摸时隐藏键盘



我有一个自定义的对话框。在对话框中,有一个可持续的内容。当我在EditText内触摸时,显示了软键盘。当我在对话框的另一个地方触摸时,我想隐藏此键盘。

我知道如何在活动中隐藏键盘。我只是不知道该如何在对话中做到这一点。

谢谢。

您可以通过使用FocusLisners来轻松执行此操作,请参见下面的代码示例:

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);
                }
            } 
        });

编辑:

<?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>

要确保获得焦点:

    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);
            }
        });

通过设置Inputmethodmanager.show_forced for Edittext:

InputMethodManager input_manager = (InputMethodManager) 
                       getSystemService(Context.INPUT_METHOD_SERVICE);
input_manager.showSoftInput(edittext, InputMethodManager.SHOW_FORCED);

最新更新