问题:显示软键盘时,自动重点是在一个EditText
-
18-09-2019 - |
题
我表示一个输入框使用 AlertDialog
.的 EditText
内部对话本身是自动的重点时,我呼叫 AlertDialog.show()
, 但软键盘是不会自动显示。
我怎么做软键盘的自动显示当的对话框所示的?(并且没有物理/硬件键盘)。类似于如何,当我按下搜索键援引的全球搜索软键盘是自动地图所示。
解决方案
您可以创建在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);
}
}
});
其他提示
有关表示键盘使用:
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);
可以创建(R20上SDK测试)的对话框之后请求软键盘
// 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);
从其他的答案代码片段工作,但它并不总是显而易见的地方放置它们的代码,特别是如果你使用的是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上,其中SHOW_FORCED将保持显示的键盘,直到它被明确地驳回开关远,即使用户返回到主屏幕或显示最近使用的应用SOFT_INPUT_STATE_ALWAYS_VISIBLE将隐藏键盘。
用于AlertDialog下面是工作的代码使用具有定义在XML中一个EditText自定义布局创建。它还设置键盘有一个“走出去”的关键,并允许它触发肯定按钮。
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);
}
让我指出一些额外的信息,以欲哭的解决方案,因为我发现它很难得到这个工作!我如何从我的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);
}
}
});
看看 此 讨论处理手动隐藏和显示IME。然而,我的感觉是,如果一个集中 EditText
是不是把IME它是因为你打电话 AlertDialog.show()
在你 OnCreate()
或者一些其他的方法是诱发之前的屏幕上实际介绍。移动它 OnPostResume()
应该修复它在这种情况下,我认为。
是的,你可以用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);
}
}
});
如果任何人是获得:
不能使从类型活动的静态参照非静态方法getSystemService(字符串)
尝试添加的上下文以getSystemService呼叫。
所以
InputMethodManager imm =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
在原始的问题涉及对话框和我的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);
尝试与使用:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
要显示的键盘,对我来说,我不得不做以下
的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);
}
我创建好的科特林-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 ); }
最后,设置onFocusChangeListener你edittext.
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { hideKeyboard(v); } } });
这是有点复杂。我没有用这种方式和它的工作。
1.At第一呼叫隐藏从窗口软输入。这将隐藏软输入,如果软键盘是可见的或者什么也不做,如果它不是。
2.Show你的对话框
3.Then只需调用切换软输入。
代码:
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); }
试了很多,但是这对我来说(科特林)什么工作:
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);
因为当你按下Home键,并移动到主屏幕,键盘将保持打开。
我知道这个问题是旧的,我认为使用扩展功能是显示键盘编辑文本更漂亮的方式
这里是我使用来显示键盘一个EditText的方法。
<强>科特林代码:强>
只需要调用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);
}
});
}
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
我把这种在的onCreate()来自动显示键盘,当我在活动