我正在使用AlertDialog显示一个输入框。当我调用AlertDialog.show()时,对话框内部的EditText会自动聚焦,但软键盘不会自动显示。
我如何使软键盘自动显示时,对话框显示?(并且没有物理/硬件键盘)。类似于当我按下Search按钮调用全局搜索时,会自动显示软键盘。
我正在使用AlertDialog显示一个输入框。当我调用AlertDialog.show()时,对话框内部的EditText会自动聚焦,但软键盘不会自动显示。
我如何使软键盘自动显示时,对话框显示?(并且没有物理/硬件键盘)。类似于当我按下Search按钮调用全局搜索时,会自动显示软键盘。
当前回答
我的方法使用了Android 11+的新方法,也支持旧版本:
fun Fragment.showKeyboard() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
ViewCompat.getWindowInsetsController(requireView())?.show(WindowInsetsCompat.Type.ime())
} else {
val focusedView = view?.findFocus() ?: view?.apply { requestFocus() }
val imm = (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
val isShowSucceeded = imm.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)
if(!isShowSucceeded) {
imm.toggleSoftInputFromWindow(
view?.windowToken, 0, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
}
}
其他回答
我有同样的问题,并解决了它与以下代码。我不确定它在有硬件键盘的手机上会有什么表现。
// TextEdit
final EditText textEdit = new EditText(this);
// Builder
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter text");
alert.setView(textEdit);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String text = textEdit.getText().toString();
finish();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
// Dialog
AlertDialog dialog = alert.create();
dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textEdit, InputMethodManager.SHOW_IMPLICIT);
}
});
dialog.show();
最初的问题涉及对话框和我的EditText是常规视图。无论如何,我认为这对你们大多数人也适用。所以这是对我有效的方法(上面建议的最高评价的方法对我没有任何作用)。下面是一个自定义的EditView,它可以做到这一点(子类化不是必需的,但我发现这对我的目的很方便,因为我还想在视图可见时捕获焦点)。
This is actually largely the same as the tidbecks answer. I actually didn't notice his answer at all as it had zero up votes. Then I was about to just comment his post, but it would have been too long, so I ended doing this post anyways. tidbeck points out that he's unsure how it works with devices having keyboards. I can confirm that the behaviour seems to be exactly the same in either case. That being such that on portrait mode the software keyboard gets popped up and on landscape it doesn't. Having the physical keyboard slid out or not makes no difference on my phone.
因为,我个人觉得行为有点尴尬,我选择使用:InputMethodManager.SHOW_FORCED。这是我想要的效果。无论朝向如何,键盘都是可见的,然而,至少在我的设备上,如果硬件键盘已经滑出,它不会弹出。
import android.app.Service;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class BringOutTheSoftInputOnFocusEditTextView extends EditText {
protected InputMethodManager inputMethodManager;
public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BringOutTheSoftInputOnFocusEditTextView(Context context) {
super(context);
init();
}
private void init() {
this.inputMethodManager = (InputMethodManager)getContext().getSystemService(Service.INPUT_METHOD_SERVICE);
this.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
BringOutTheSoftInputOnFocusEditTextView.this.inputMethodManager.showSoftInput(BringOutTheSoftInputOnFocusEditTextView.this, InputMethodManager.SHOW_FORCED);
}
}
});
}
@Override
protected void onVisibilityChanged(View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (visibility == View.VISIBLE) {
BringOutTheSoftInputOnFocusEditTextView.this.requestFocus();
}
}
}
我的方法使用了Android 11+的新方法,也支持旧版本:
fun Fragment.showKeyboard() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
ViewCompat.getWindowInsetsController(requireView())?.show(WindowInsetsCompat.Type.ime())
} else {
val focusedView = view?.findFocus() ?: view?.apply { requestFocus() }
val imm = (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
val isShowSucceeded = imm.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)
if(!isShowSucceeded) {
imm.toggleSoftInputFromWindow(
view?.windowToken, 0, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
}
}
问题似乎是,因为你输入文本的地方最初是隐藏的(或嵌套或其他),AlertDialog自动设置标志WindowManager.LayoutParams。FLAG_ALT_FOCUSABLE_IM或WindowManager.LayoutParams。FLAG_NOT_FOCUSABLE,这样就不会触发软输入来显示。
解决这个问题的方法是添加以下内容:
(...)
// Create the dialog and show it
Dialog dialog = builder.create()
dialog.show();
// After show (this is important specially if you have a list, a pager or other view that uses a adapter), clear the flags and set the soft input mode
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
来自其他答案的代码片段也可以工作,但将它们放在代码中的哪个位置并不总是很明显,特别是在使用AlertDialog时。Builder和遵循官方对话框教程,因为它不使用最终AlertDialog…或alertDialog.show()。
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
更可取
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
因为如果焦点从EditText移开,SOFT_INPUT_STATE_ALWAYS_VISIBLE将隐藏键盘,而SHOW_FORCED将保持键盘显示,直到显式地关闭,即使用户返回到主屏幕或显示最近的应用程序。
下面是使用自定义布局和XML定义的EditText创建的AlertDialog的工作代码。它还设置键盘有一个“go”键,并允许它触发积极按钮。
alert_dialog.xml:
<RelativeLayout
android:id="@+id/dialogRelativeLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<!-- android:imeOptions="actionGo" sets the keyboard to have a "go" key instead of a "new line" key. -->
<!-- android:inputType="textUri" disables spell check in the EditText and changes the "go" key from a check mark to an arrow. -->
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:imeOptions="actionGo"
android:inputType="textUri"/>
</RelativeLayout>
AlertDialog.java:
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
public class CreateDialog extends AppCompatDialogFragment {
// The public interface is used to send information back to the activity that called CreateDialog.
public interface CreateDialogListener {
void onCreateDialogCancel(DialogFragment dialog);
void onCreateDialogOK(DialogFragment dialog);
}
CreateDialogListener mListener;
// Check to make sure that the activity that called CreateDialog implements both listeners.
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (CreateDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement CreateDialogListener.");
}
}
// onCreateDialog requires @NonNull.
@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
LayoutInflater customDialogInflater = getActivity().getLayoutInflater();
// Setup dialogBuilder.
alertDialogBuilder.setTitle(R.string.title);
alertDialogBuilder.setView(customDialogInflater.inflate(R.layout.alert_dialog, null));
alertDialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mListener.onCreateDialogCancel(CreateDialog.this);
}
});
alertDialogBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mListener.onCreateDialogOK(CreateDialog.this);
}
});
// Assign the resulting built dialog to an AlertDialog.
final AlertDialog alertDialog = alertDialogBuilder.create();
// Show the keyboard when the dialog is displayed on the screen.
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
// We need to show alertDialog before we can setOnKeyListener below.
alertDialog.show();
EditText editText = (EditText) alertDialog.findViewById(R.id.editText);
// Allow the "enter" key on the keyboard to execute "OK".
editText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button, select the PositiveButton "OK".
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
// Trigger the create listener.
mListener.onCreateDialogOK(CreateDialog.this);
// Manually dismiss alertDialog.
alertDialog.dismiss();
// Consume the event.
return true;
} else {
// If any other key was pressed, do not consume the event.
return false;
}
}
});
// onCreateDialog requires the return of an AlertDialog.
return alertDialog;
}
}