我正在使用AlertDialog显示一个输入框。当我调用AlertDialog.show()时,对话框内部的EditText会自动聚焦,但软键盘不会自动显示。
我如何使软键盘自动显示时,对话框显示?(并且没有物理/硬件键盘)。类似于当我按下Search按钮调用全局搜索时,会自动显示软键盘。
我正在使用AlertDialog显示一个输入框。当我调用AlertDialog.show()时,对话框内部的EditText会自动聚焦,但软键盘不会自动显示。
我如何使软键盘自动显示时,对话框显示?(并且没有物理/硬件键盘)。类似于当我按下Search按钮调用全局搜索时,会自动显示软键盘。
看看这个手动隐藏和显示IME的讨论。然而,我的感觉是,如果一个集中的EditText没有带来IME,这是因为你正在调用AlertDialog.show()在你的OnCreate()或一些其他方法,在屏幕实际呈现之前被唤起。移动到OnPostResume()应该在这种情况下修复它,我相信。
您可以在AlertDialog的EditText上创建一个焦点侦听器,然后获取AlertDialog的窗口。从那里你可以通过调用setSoftInputMode来显示软键盘。
final AlertDialog dialog = ...;
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
我有同样的问题,并解决了它与以下代码。我不确定它在有硬件键盘的手机上会有什么表现。
// 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();
}
}
}
你可以在创建对话框后立即请求软键盘(在SDK - r20上测试)
// create dialog
final AlertDialog dialog = ...;
// request keyboard
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
我找到了这个例子http://android-codes-examples.blogspot.com/2011/11/show-or-hide-soft-keyboard-on-opening.html。在alert.show()之前添加以下代码。
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
如果有人想:
不能从Activity类型对非静态方法getSystemService(String)进行静态引用
尝试向getSystemService调用添加上下文。
So
InputMethodManager imm =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
是的,你可以用setOnFocusChangeListener来做,它会帮助你。
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
显示键盘使用情况:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
隐藏键盘使用:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
让我指出一些额外的信息,解决yuku,因为我发现很难得到这个工作!我如何从我的AlertDialog. builder获得AlertDialog对象?嗯,这是alert.show()执行的结果:
final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
alert.setView(input);
// do what you need, like setting positive and negative buttons...
final AlertDialog dialog = alert.show();
input.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
<activity
...
android:windowSoftInputMode="stateVisible" >
</activity>
or
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
这是一个很好的例子:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scrollID"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1" >
<LinearLayout
android:id="@+id/test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="true"
android:orientation="horizontal"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:weightSum="1" >
<EditText
android:id="@+id/txtInpuConversation"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:hint="@string/edt_Conversation" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btnSend"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="@string/btn_Conversation" />
</LinearLayout>
</LinearLayout>
为什么这个答案-因为上面的解决方案将显示你的键盘,但它不会消失,如果你点击任何其他的编辑文本。因此,当EditText失去焦点时,您需要做一些事情使键消失。
你可以通过以下步骤来实现这一点:
Make the parent view(content view of your activity) clickable and focusable by adding the following attributes android:clickable="true" android:focusableInTouchMode="true" Implement a hideKeyboard() method public void hideKeyboard(View view) { InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY ); } Lastly, set the onFocusChangeListener of your edittext. edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { hideKeyboard(v); } } });
问题似乎是,因为你输入文本的地方最初是隐藏的(或嵌套或其他),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);
试着使用:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
这有点棘手。我这样做了,而且成功了。
1.在第一次调用时,从窗口中隐藏软输入。如果软键盘可见,这将隐藏软输入;如果软键盘不可见,则不执行任何操作。
2.展示你的对话
3.然后简单地调用切换软输入。
代码:
InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//hiding soft input
inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWindowToken(), 0);
//show dialog
yourDialog.show();
//toggle soft input
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.SHOW_IMPLICIT);
要显示键盘,对我来说,我必须执行以下操作
Android文本字段:设置焦点+软输入编程
基本上解决方案如下
@Override
public void onResume() {
super.onResume();
//passwordInput.requestFocus(); <-- that doesn't work
passwordInput.postDelayed(new ShowKeyboard(), 325); //250 sometimes doesn't run if returning from LockScreen
}
ShowKeyboard在哪里
private class ShowKeyboard implements Runnable {
@Override
public void run() {
passwordInput.setFocusableInTouchMode(true);
//passwordInput.requestFocusFromTouch(); //this gives touch event to launcher in background -_-
passwordInput.requestFocus();
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(passwordInput, 0);
}
}
在成功输入之后,我还确保隐藏了键盘
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(getView().getWindowToken(), 0);
好吧,这是一个相当老的帖子,仍然有一些东西需要添加。这是两个简单的方法,帮助我保持键盘在控制之下,他们工作得非常完美:
显示键盘
public void showKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View v = getCurrentFocus();
if (v != null)
imm.showSoftInput(v, 0);
}
隐藏键盘
public void hideKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View v = getCurrentFocus();
if (v != null)
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
来自其他答案的代码片段也可以工作,但将它们放在代码中的哪个位置并不总是很明显,特别是在使用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;
}
}
试试这个
SomeUtils.java showKeyboard(Activity Activity, boolean show) { InputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); 如果(显示) inputMethodManager.toggleSoftInput (InputMethodManager.SHOW_FORCED 0); 其他的 inputMethodManager.toggleSoftInput (InputMethodManager.HIDE_IMPLICIT_ONLY 0); }
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
我在onCreate()中调用它来自动显示键盘,当我进入活动时。
将这些方法放在Util类中,并在任何地方使用。
科特林
fun hideKeyboard(activity: Activity) {
val view = activity.currentFocus
val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
assert(view != null)
methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
private fun showKeyboard(activity: Activity) {
val view = activity.currentFocus
val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
assert(view != null)
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
Java
public static void hideKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
assert methodManager != null && view != null;
methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
private static void showKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
assert methodManager != null && view != null;
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
看看https://stackoverflow.com/a/39144104/2914140,我简化了一点:
// In onCreateView():
view.edit_text.run {
requestFocus()
post { showKeyboard(this) }
}
fun showKeyboard(view: View) {
val imm = view.context.getSystemService(
Context.INPUT_METHOD_SERVICE) as InputMethodManager?
imm?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
它比https://stackoverflow.com/a/11155404/2914140:好
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
因为当你按Home键并移动到主屏幕时,键盘会保持打开状态。
我创建了很好的kotlin-esqe扩展函数,如果有人感兴趣的话
fun Activity.hideKeyBoard() {
val view = this.currentFocus
val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
assert(view != null)
methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
fun Activity.showKeyboard() {
val view = this.currentFocus
val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
assert(view != null)
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
尝试了很多,但这对我来说是有效的(kotlin):
val dialog = builder.create()
dialog.setOnShowListener {
nameEditText.requestFocus()
val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
s?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
dialog.setOnDismissListener {
val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
s?.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}
dialog.show()
我知道这个问题很老了,因为我认为使用扩展函数是一种更漂亮的方式来显示编辑文本的键盘
下面是我用来显示编辑文本键盘的方法。
芬兰湾的科特林代码: 只需要调用edittext.showKeyboard()
fun EditText.showKeyboard() {
post {
requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
Java代码:
public static void showKeyboard(EditText editText) {
editText.post(new Runnable() {
@Override
public void run() {
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) editText.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
});
}
在AlertDialog中从EditText显示软键盘的问题可能是在AlertDialog.show()中,因为在显示AlertDialog之后应用了EditText。我不确定所有版本的API都是这样,但我认为解决方案来自API级别21,因为它来自AlertDialog.create(),它应该在AlertDialog.show()之前调用。
这是我对这种情况的最佳解决方案。首先,在某个地方创建:
private int showKeyboard(View view) {
final InputMethodManager inputManager = (InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager != null) {
boolean isShown = inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); // flag=InputMethodManager.SHOW_IMPLICIT ili =
return (isShown) ? 1: -1;
}
return 0;
}
然后,在AlertDialog之后。生成器生成器= new AlertDialog.Builder(requireContext());继续:
EditText editText = new EditText(requireContext());
builder.setView(editText);
// ... put positive-negative buttons, and etc ...
AlertDialog dialog = builder.create(); // Create dialog from builder
dialog.setCancelable(false); // If you need
Handler handler = new Handler();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) { // 1. When a dialog is displayed
editText.requestFocus();
Runnable runnable = new Runnable() { // create one runnable
int counter = 0;
public void run() {
int status = showKeyboard(editText); // 2. Call func.above for keyboard, but...
if(status == -1 && counter < 10){ handler.postDelayed(this, 100); counter ++; } // ...if it inst shown call again after 100ms
}
};
runnable.run(); // Execute runnable first time here
}
});
dialog.show();
不要忘记导入android.os.Handler;等等;-)
感谢大家的投票。
我的方法使用了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)
}
}
}
这对我很有用。我为对话框设置了一个OnShowListener,在那个监听器中,我为文本字段设置了一个onFocusChangeListener,在那个FocusChangeListener中,我用100ms的延迟调用showSoftInput,然后删除FocusChangeListener,所以它只处理第一个焦点变化。
当调用dialog.show()时,OnShowListener被调用,它请求文本字段的焦点。当文本字段获得焦点时,将调用FocusChangeListener并最终显示键盘。
val views = DialogBinding.inflate(layoutInflater) // layout with 'textfield'
val dialog = MaterialAlertDialogBuilder(requireContext())
.setTitle("Exercise")
.setView(views.root)
...
.create()
dialog.setOnShowListener {
views.textfield.onFocusChangeListener = View.OnFocusChangeListener { view, _ ->
view.postDelayed({
(view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(view, 0)
}, 100)
views.textfield.onFocusChangeListener = null
}
views.repcount.requestFocus()
}
dialog.show()
我们可以在对话显示时默认打开键盘
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
你可以在EditText上附加onFocusListener或在AlertDialog上附加onShowListener,并添加以下内容:
val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
edittext.setShowSoftInputOnFocus(真正的);是关于这个问题的最流畅的解决方案。
AlertDialog.Builder alertSearch = new AlertDialog.Builder(activity);
alertSearch.setIcon(R.drawable.ic_launcher);
alertSearch.setTitle("Search");
final EditText edittext = new EditText(activity);
edittext.setSingleLine();
edittext.setHint("...");
edittext.setText(SearchString);
在聚焦时设置键盘
edittext.setShowSoftInputOnFocus(true);
获得焦点
edittext.requestFocus();
And
alertSearch.setView(edittext);
alertSearch.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do something
act.recreate();
}
});
alertSearch.show();