使用对话框启动活动时自动打开键盘

时间:2018-10-09 12:58:45

标签: android android-dialog

我创建了一个快捷方式,其目的是启动一个活动。
在活动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);
}

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

我还在this question中尝试了建议的解决方案,但没有一个起作用。

2 个答案:

答案 0 :(得分:0)

请尝试以下操作:

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

答案 1 :(得分:0)

尝试一下,

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager != null) {
                    inputMethodManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
                }