Android中弹框中Edittext自动弹出键盘

511 阅读1分钟

在Android的普通页面上, 如果想让键盘弹出, 可以用下面方法

        try {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(tokenView, InputMethodManager.SHOW_IMPLICIT);
        } catch (Exception e) {
            e.printStackTrace();
        }

当然, 隐藏键盘可以用下面的代码:

        try {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(tokenView.getWindowToken(), InputMethodManager.SHOW_IMPLICIT);
        } catch (Exception e) {
            e.printStackTrace();
        }

但是这些方法对于弹框中的Edittext并不生效, 很简单, 在Dialog的theme中加上

<item name="android:windowSoftInputMode">stateAlwaysVisible</item>

就可以了 完整的theme如下:

    <style name="normalDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowBackground">@color/white_background</item>
        <item name="android:colorBackground">@color/white_background</item>
        <item name="android:backgroundDimEnabled">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowSoftInputMode">stateAlwaysVisible</item>
    </style>