首页 > 解决方案 > 使用对话框启动活动时自动打开键盘

问题描述

我创建了一个快捷方式,它的意图是启动一个活动。
在活动中onCreate,我展示了一个android.app.Dialog自定义视图。
我想与活动/对话框一起打开键盘。
对话框布局:

 <EditText
    android:id="@+id/reminderEditText"
    android:inputType="text"
    android:maxLength="60"
    android:maxLines="1"
    android:hint="@string/remind_to"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <requestFocus />
</EditText>

清单中的活动声明:

    <activity
        android:name=".ReminderActivity"
        android:windowSoftInputMode="stateAlwaysVisible"
        android:label="@string/new_reminder"
        android:exported="true"
        android:theme="@android:style/Theme.Translucent.NoTitleBar"/>

活动onCreate()

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.dialog_reminder, null);
    EditText editText = view.findViewById(R.id.reminderEditText);
    editText.requestFocus();

    MaterialStyledDialog dialog = new MaterialStyledDialog.Builder(this)
            .setIcon(R.drawable.ic_post_it_2)
            .setCustomView(view, 20, 20, 20, 0)
            .setPositiveText(android.R.string.ok)
            .autoDismiss(true) // close dialog on callbakcs
            .setCancelable(false) // not cancellable on outside touch
            .show();
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}

如您所见,我已经尝试了所有可以在网上找到的关于自动显示键盘的解决方案,但都没有成功。

我也尝试了这个问题中建议的解决方案,但没有一个有效。

标签: androidandroid-dialog

解决方案


请试试这个:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

推荐阅读