我的布局中有一个EditText和一个Button。

在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?


当前回答

对于kotlin用户,这里有一个kotlin扩展方法,它适用于我的用例:

fun View.hideKeyboard() {
    val imm = this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}

将其放在名为ViewExtensions的文件中(或其他文件),并像普通方法一样在视图中调用它。

其他回答

我的解决方案:

用活动构造它(视图是可选的),使用处理程序发布它(有一些延迟,例如100ms更好)。直接调用输入管理器有时不起作用。只有在工作时才能获得“活动”。我认为这很正常。

如果您可以在通话时获取根视图组或编辑视图,只需发送它即可获得更好的结果。

public class CloseSoftKeyboardRunnable implements Runnable
{
    Activity activity;
    View view;  // for dialog will occur context getcurrentfocus == null. send a rootview to find currentfocus.

    public CloseSoftKeyboardRunnable(Activity activity, View view)
    {
        this.activity = activity;
        this.view = view;
    }

    public CloseSoftKeyboardRunnable(Activity activity)
    {
        this.activity = activity;
    }
    @Override
    public void run() {
        if (!activity.isFinishing())
        {
            InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);

            if (view == null) {
                view = activity.getCurrentFocus();
            }
            else
            {
                try {
                    view = ((ViewGroup)view).getFocusedChild();
                }
                catch ( Exception e) {}
            }

            Window window =  activity.getWindow();
            
            if (window != null)
            {
                if (view == null) {
                    try {
                        view = window.getDecorView();
                        view = ((ViewGroup)view).getFocusedChild();
                    }
                    catch ( Exception e) {}
                }

                if (view == null) {
                    view = window.getDecorView();
                }

                if (view != null) {
                    if (view instanceof EditText)
                    {
                        EditText edittext = ((EditText) view);
                        edittext.setText(edittext.getText().toString()); // reset edit text bug on some keyboards bug
                        edittext.clearFocus();
                    }

                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            }
        }
    }
}

只需在特定活动的AndroidManifest中添加以下行。

<activity
        android:name=".MainActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustPan"/>

这对我有用。。

EditText editText=(EditText)findViewById(R.id.edittext1);

放在onClick()中的代码行下面

editText.setFocusable(false);
editText.setFocusableInTouchMode(true);

这里隐藏键盘,当我们单击按钮时,当我们触摸EditText键盘时,将显示。

(OR)

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

我创建了一个布局,部分来自xml,部分来自自定义布局引擎,所有这些都在代码中处理。对我来说,唯一有效的方法是跟踪键盘是否打开,并使用如下键盘切换方法:

public class MyActivity extends Activity
{
    /** This maintains true if the keyboard is open. Otherwise, it is false. */
    private boolean isKeyboardOpen = false;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater;
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(context.getResources().getIdentifier("main", "layout", getPackageName()), null);

        setContentView(contentView);
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() 
        {
            public void onGlobalLayout() 
            {
                Rect r = new Rect();
                contentView.getWindowVisibleDisplayFrame(r);
                int heightDiff = contentView.getRootView().getHeight() - (r.bottom - r.top);
                if (heightDiff > 100) 
                    isKeyboardVisible = true;
                else
                    isKeyboardVisible = false;
             });
         }
    }

    public void closeKeyboardIfOpen()
    {
        InputMethodManager imm;
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isKeyboardVisible)
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    }   
}

如果有人感兴趣的话,我已经为Kotlin写了一个小扩展,但没有太多测试:

fun Fragment.hideKeyboard(context: Context = App.instance) {
    val windowToken = view?.rootView?.windowToken
    windowToken?.let {
        val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)
    }
}

App.instance是存储在Application中的静态“this”Application对象

更新:在某些情况下,windowToken为空。我增加了使用反射来检测键盘是否关闭的额外关闭方式

/**
 * If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
 *
 * @param useReflection - whether to use reflection in case of no window token or not
 */
fun Fragment.hideKeyboard(context: Context = MainApp.instance, useReflection: Boolean = true) {
    val windowToken = view?.rootView?.windowToken
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    windowToken?.let {
        imm.hideSoftInputFromWindow(windowToken, 0)
    } ?: run {
        if (useReflection) {
            try {
                if (getKeyboardHeight(imm) > 0) {
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
                }
            } catch (exception: Exception) {
                Timber.e(exception)
            }
        }
    }
}

fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int