我正在使用显示一个输入框AlertDialog
。在EditText
该对话框中本身自动对焦,当我打电话AlertDialog.show()
,但软键盘未自动显示。
显示对话框时,如何使软键盘自动显示?(并且没有物理/硬件键盘)。类似于当我按下“搜索”按钮以调用全局搜索时,自动显示软键盘。
我正在使用显示一个输入框AlertDialog
。在EditText
该对话框中本身自动对焦,当我打电话AlertDialog.show()
,但软键盘未自动显示。
显示对话框时,如何使软键盘自动显示?(并且没有物理/硬件键盘)。类似于当我按下“搜索”按钮以调用全局搜索时,自动显示软键盘。
Answers:
您可以在创建一个焦点侦听器EditText
上AlertDialog
,然后得到AlertDialog
的Window
。从那里,您可以通过调用显示软键盘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);
}
}
});
final AlertDialog dialog = builder.create()
,然后show
在对话框中而不是在构建器上,从构建器获取对话框。
显示键盘使用:
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);
您可以在创建对话框后立即请求软键盘(在SDK-r20上测试)
// create dialog
final AlertDialog dialog = ...;
// request keyboard
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();
我发现了这个示例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
...
android:windowSoftInputMode="stateVisible" >
</activity>
要么
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
stateHidden
,当我检测到用户正在创建新项目时,我使用您提到的代码行显示了键盘。:)再次感谢。
((Activity) context).getWindow()....
。
其他答案的代码段也可以工作,但是将代码段放在代码中的位置并不总是很明显,尤其是如果您使用AlertDialog.Builder
并遵循官方对话框教程,因为它没有使用final 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;
}
}
好吧,这是一篇很老的文章,仍然有一些要添加的内容。
这是2种简单的方法,可以帮助我控制键盘,并且效果非常理想:
显示键盘
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);
}
getCurrentFocus()
啊
Activity
。
让我为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);
}
}
});
是的,您可以使用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);
}
}
});
我知道这个问题很老,因为我认为使用扩展功能是一种显示键盘以显示编辑文本的更漂亮的方法
这是我用来显示键盘的文本的方法。
Kotlin代码:
只需调用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);
}
});
}
最初的问题与对话框有关,而我的EditText位于常规视图上。无论如何,我怀疑这也适用于大多数人。所以这是对我有用的方法(上面建议的最高评分方法对我没有任何帮助)。这是一个执行此操作的自定义EditView(不必进行子类化,但是我发现它很方便,因为我想在视图变为可见时也能抓住焦点)。
这实际上与tidbecks的答案基本相同。实际上,我根本没有注意到他的答案,因为它的票数为零。然后我只想评论他的帖子,但是那太久了,所以无论如何我都结束了这篇帖子。tidbeck指出,他不确定带键盘的设备如何使用。我可以确认两种情况下的行为似乎完全相同。这样一来,在纵向模式下,软件键盘会弹出,而在横向模式下则不会。物理键盘是否滑出对我的手机没有影响。
因为,我个人觉得有点尴尬,我选择使用的行为: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();
}
}
}
问题似乎在于,由于最初输入文本的位置是隐藏的(或嵌套的或类似的东西),因此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);
为了显示键盘,对我来说,我必须执行以下操作
Android TextField:以编程方式设置焦点+软输入
本质上,解决方案如下
@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);
将这些方法放在您的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)
}
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);
}
我创建了不错的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)
}
这是适合您的好样本:
<?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
。因此,您需要采取一些措施使EditText
失去焦点时键盘消失。
您可以通过执行以下步骤来实现:
通过添加以下属性,使父视图(您的活动的内容视图)可单击和可聚焦
android:clickable="true"
android:focusableInTouchMode="true"
实现hideKeyboard()方法
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY );
}
最后,设置您的edittext的onFocusChangeListener。
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
这有点棘手。我以这种方式做到了,而且奏效了。
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);
尝试这个
SomeUtils.java
public static void showKeyboard(Activity activity, boolean show) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); if(show) inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0); else inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0); }
尝试了很多,但这对我有用(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()
看着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);
因为当您按下主屏幕按钮并移至主屏幕时,键盘将保持打开状态。