提问人: 提问时间:7/10/2009 最后编辑:30 revs, 18 users 21%Vidar Vestnes 更新时间:10/18/2023 访问量:1822686
如何以编程方式关闭/隐藏 Android 软键盘?
How can I close/hide the Android soft keyboard programmatically?
问:
我的布局中有一个和一个。EditText
Button
在编辑字段中输入并单击后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但是在哪里可以找到它的示例?Button
答:
您可以使用 InputMethodManager 强制 Android 隐藏虚拟键盘,调用 hideSoftInputFromWindow
,传入包含焦点视图的窗口的令牌。
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
这将强制在所有情况下隐藏键盘。在某些情况下,您需要作为第二个参数传入,以确保仅在用户未显式强制显示键盘(通过按住菜单)时隐藏键盘。InputMethodManager.HIDE_IMPLICIT_ONLY
注意:如果您想在 Kotlin 中执行此操作,请使用:context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
Kotlin 语法
// Only runs if there is a view that is currently focused
this.currentFocus?.let { view ->
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(view.windowToken, 0)
}
评论
getSystemService()
Context
Class
requiredContext
Fragment
getActivity().getSystemService()...
请尝试以下代码onCreate()
EditText edtView = (EditText) findViewById(R.id.editTextConvertValue);
edtView.setInputType(InputType.TYPE_NULL);
评论
editView.setInputType(InputType.TYPE_NULL);
隐藏软键盘也很有用:
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
这可用于禁止使用软键盘,直到用户实际触摸 editText 视图。
评论
Meier的解决方案也适用于我。就我而言,我的应用程序的顶层是一个选项卡主机,我想在切换选项卡时隐藏关键字 - 我从选项卡主机视图获取窗口令牌。
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tabHost.getApplicationWindowToken(), 0);
}
}
更新:我不知道为什么这个解决方案不再起作用了(我刚刚在 Android 23 上进行了测试)。请改用 Saurabh Pareek 的解决方案。在这里:
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
旧答案:
//Show soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//hide keyboard :
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
评论
I don't know why this solution is not work any more
- 因为它是 Android,一切都会改变,也许部分是糟糕的设计......我们粗心大意地写,然后我们删除所有内容并重写所有内容。
如果要在单元测试或功能测试期间关闭软键盘,可以通过单击测试中的“后退按钮”来实现:
// Close the soft keyboard from a Test
getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
我把“后退按钮”放在引号里,因为上面的内容不会触发相关活动的。它只是关闭键盘。onBackPressed()
在继续之前,请确保暂停一会儿,因为关闭后退按钮需要一段时间,因此在短暂的暂停(1 秒足够长的 ime)之前,不会记录对视图等的后续单击。
如果这里的所有其他答案都不能像您希望的那样适合您,还有另一种手动控制键盘的方法。
创建一个函数,用它来管理一些 的属性:EditText
public void setEditTextFocus(boolean isFocused) {
searchEditText.setCursorVisible(isFocused);
searchEditText.setFocusable(isFocused);
searchEditText.setFocusableInTouchMode(isFocused);
if (isFocused) {
searchEditText.requestFocus();
}
}
然后,确保打开/关闭键盘的 onFocus:EditText
searchEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (v == searchEditText) {
if (hasFocus) {
// Open keyboard
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(searchEditText, InputMethodManager.SHOW_FORCED);
} else {
// Close keyboard
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
}
}
}
});
现在,每当您想手动打开键盘时,请调用:
setEditTextFocus(true);
对于结束电话会议:
setEditTextFocus(false);
评论
通过这样的搜索,在这里我找到了一个适合我的答案
// Show soft-keyboard:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
// Hide soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
我还有一种隐藏键盘的解决方案:
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
这里在 的位置和 的位置传递。它将强行关闭软键盘。HIDE_IMPLICIT_ONLY
showFlag
0
hiddenFlag
评论
我正在使用自定义键盘输入十六进制数字,因此我无法显示 IMM 键盘......
在 v3.2.4_r1 中添加了控制天气或在 TextView 获得焦点时不显示键盘,但它仍然隐藏,因此必须使用反射:setSoftInputShownOnFocus(boolean show)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
try {
Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class);
method.invoke(mEditText, false);
} catch (Exception e) {
// Fallback to the second method
}
}
对于旧版本,我得到了非常好的结果(但远非完美),在我的根视图的帮助下添加了一个,然后检查键盘是否显示如下:OnGlobalLayoutListener
ViewTreeObserver
@Override
public void onGlobalLayout() {
Configuration config = getResources().getConfiguration();
// Dont allow the default keyboard to show up
if (config.keyboardHidden != Configuration.KEYBOARDHIDDEN_YES) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mRootView.getWindowToken(), 0);
}
}
最后一种解决方案可能会在一瞬间显示键盘并弄乱选择手柄。
当键盘进入全屏时,不会调用 onGlobalLayout。若要避免这种情况,请使用 TextView#setImeOptions(int) 或在 TextView XML 声明中:
android:imeOptions="actionNone|actionUnspecified|flagNoFullscreen|flagNoExtractUi"
更新:刚刚找到了对话框用来从不显示键盘并且适用于所有版本的内容:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
评论
protected void hideSoftKeyboard(EditText input) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
评论
input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)
input.setInputType(0);
inputType
EditText
以下是在 Mono for Android(又名 MonoDroid)中执行此操作的方法
InputMethodManager imm = GetSystemService (Context.InputMethodService) as InputMethodManager;
if (imm != null)
imm.HideSoftInputFromWindow (searchbox.WindowToken , 0);
评论
searchbox
您还可以考虑在 EditText 上使用 setImeOption。
我只是有一个非常模拟的情况,我的布局包含一个 EditText 和一个搜索按钮。当我发现我可以在我的 editText 上将 ime 选项设置为“actionSearch”时,我意识到我甚至不再需要搜索按钮了。软键盘(在此模式下)有一个搜索图标,可用于启动搜索(键盘会按预期自行关闭)。
评论
上面的答案适用于不同的场景,但如果你想将键盘隐藏在视图中,并且努力获得正确的上下文,请尝试以下操作:
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
hideSoftKeyBoardOnTabClicked(v);
}
}
private void hideSoftKeyBoardOnTabClicked(View v) {
if (v != null && context != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
并获取上下文,请从构造函数中获取它:)
public View/RelativeLayout/so and so (Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
init();
}
有时,您想要的只是 Enter 按钮来折叠您拥有的属性框keyboard
EditText
android:imeOptions="actionDone"
这会将“Enter”按钮更改为“完成”按钮,该按钮将关闭键盘。
评论
android:imeOptions="actionDone"
android:singleLine="true"
我部分从 xml 创建了一个布局,部分从自定义布局引擎创建了一个布局,这些引擎都是在代码中处理的。唯一对我有用的是跟踪键盘是否打开,并使用键盘切换方法,如下所示:
public class MyActivity extends Activity
{
/** This maintains true if the keyboard is open. Otherwise, it is false. */
private boolean isKeyboardOpen = false;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LayoutInflater inflater;
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(context.getResources().getIdentifier("main", "layout", getPackageName()), null);
setContentView(contentView);
contentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
public void onGlobalLayout()
{
Rect r = new Rect();
contentView.getWindowVisibleDisplayFrame(r);
int heightDiff = contentView.getRootView().getHeight() - (r.bottom - r.top);
if (heightDiff > 100)
isKeyboardVisible = true;
else
isKeyboardVisible = false;
});
}
}
public void closeKeyboardIfOpen()
{
InputMethodManager imm;
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (isKeyboardVisible)
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
}
就我而言,我在操作栏中使用了 SearchView。用户执行搜索后,键盘将再次弹出。
使用 InputMethodManager 不会关闭键盘。我必须清除焦点并将搜索视图的可聚焦设置为false:
mSearchView.clearFocus();
mSearchView.setFocusable(false);
评论
clearFocus()
到目前为止,Saurabh Pareek有最好的答案。
不过,还不如使用正确的标志。
/* hide keyboard */
((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
/* show keyboard */
((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
实际使用示例
/* click button */
public void onClick(View view) {
/* hide keyboard */
((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
/* start loader to check parameters ... */
}
/* loader finished */
public void onLoadFinished(Loader<Object> loader, Object data) {
/* parameters not valid ... */
/* show keyboard */
((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
/* parameters valid ... */
}
我花了两天多的时间研究线程中发布的所有解决方案,发现它们以一种或另一种方式缺乏。我的确切要求是有一个按钮,该按钮将具有 100% 的可靠性,可以显示或隐藏屏幕键盘。当键盘处于隐藏状态时,无论用户单击什么输入字段,都不应重新出现。当它处于可见状态时,无论用户单击什么按钮,键盘都不应消失。这需要在 Android 2.2+ 上一直工作到最新设备。
您可以在我的应用程序干净 RPN 中看到它的工作实现。
在许多不同的手机(包括 froyo 和 gingerbread 设备)上测试了许多建议的答案后,很明显 android 应用程序可以可靠地:
- 暂时隐藏键盘。当用户 聚焦新的文本字段。
- 活动开始时显示键盘 并在活动上设置一个标志,指示他们应 始终可见。仅当活动 正在初始化。
- 将活动标记为从不显示或允许使用 键盘。仅当活动 正在初始化。
对我来说,暂时隐藏键盘是不够的。在某些设备上,一旦聚焦新的文本字段,它就会重新出现。由于我的应用在一个页面上使用多个文本字段,因此聚焦新的文本字段将导致隐藏的键盘再次弹出。
遗憾的是,列表中的第 2 项和第 3 项仅在启动活动时才具有可靠性。活动变为可见后,您将无法永久隐藏或显示键盘。诀窍是在用户按下键盘切换按钮时实际重新启动您的活动。在我的应用中,当用户按下切换键盘按钮时,将运行以下代码:
private void toggleKeyboard(){
if(keypadPager.getVisibility() == View.VISIBLE){
Intent i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
Bundle state = new Bundle();
onSaveInstanceState(state);
state.putBoolean(SHOW_KEYBOARD, true);
i.putExtras(state);
startActivity(i);
}
else{
Intent i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
Bundle state = new Bundle();
onSaveInstanceState(state);
state.putBoolean(SHOW_KEYBOARD, false);
i.putExtras(state);
startActivity(i);
}
}
这会导致当前活动将其状态保存到 Bundle 中,然后启动该活动,传递一个布尔值,该布尔值指示是否应显示或隐藏键盘。
在 onCreate 方法中,运行以下代码:
if(bundle.getBoolean(SHOW_KEYBOARD)){
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(newEquationText,0);
getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
else{
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}
如果应显示软键盘,则告知 InputMethodManager 显示键盘,并指示窗口使软输入始终可见。如果应隐藏软键盘,则设置WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM。
这种方法在我测试过的所有设备上都能可靠地工作——从运行 android 4 的 2.2 岁的 HTC 手机到运行 4.2.2 的 nexus 7。这种方法的唯一缺点是您需要小心处理后退按钮。由于我的应用程序基本上只有一个屏幕(它是一个计算器),我可以覆盖 onBackPressed() 并返回设备主屏幕。
评论
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
在对 onTouchListener 进行调用后:
findViewById(android.R.id.content).setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Utils.hideSoftKeyboard(activity);
return false;
}
});
评论
绝望地在这里尝试了所有方法,结合所有方法,当然键盘在Android 4.0.3中不会关闭(它在Honeicomb AFAIR中确实有效)。
然后突然我发现了一个明显成功的组合:
textField.setRawInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_VARIATION_NORMAL);
结合您常用的食谱
blahblaj.hideSoftInputFromWindow ...
希望这能阻止有人自杀......我离它很近。当然,我不知道它为什么会起作用。
为了帮助澄清这种疯狂,我想首先代表所有 Android 用户为 Google 对软键盘的彻头彻尾的荒谬处理道歉。对于同一个简单的问题,之所以有这么多答案,每个答案都不同,是因为这个 API 和 Android 中的许多其他 API 一样,设计得很糟糕。我想不出任何礼貌的方式来表达它。
我想隐藏键盘。我希望为 Android 提供以下声明:.结束。谢谢。但是Android有一个问题。您必须使用 隐藏键盘。好的,好的,这是 Android 的键盘 API。但!您需要拥有 IMM 才能访问 IMM。现在我们有一个问题。我可能想从没有任何用处或不需要任何的静态或实用程序类中隐藏键盘。或者更糟糕的是,IMM 要求您指定要隐藏键盘的内容(甚至更糟的是,内容)。Keyboard.hide()
InputMethodManager
Context
Context
View
Window
这就是隐藏键盘如此具有挑战性的原因。亲爱的谷歌:当我查找蛋糕的食谱时,地球上没有人会拒绝向我提供食谱,除非我首先回答蛋糕将被谁吃掉以及在哪里吃!!RecipeProvider
这个悲伤的故事以丑陋的事实结束:要隐藏 Android 键盘,您需要提供 2 种形式的身份证明:a 和 a 或 a .Context
View
Window
我创建了一个静态实用程序方法,只要您从 .Activity
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view = activity.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(activity);
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
请注意,此实用程序方法仅在从 !上述方法调用目标以获取正确的窗口令牌。Activity
getCurrentFocus
Activity
但是,假设您想将键盘隐藏在 ?您不能使用上述方法:EditText
DialogFragment
hideKeyboard(getActivity()); //won't work
这是行不通的,因为您将传递对 的 host 的引用,该主机在显示时没有集中的控制!哇!因此,为了隐藏键盘的碎片,我求助于较低级别、更常见且更丑陋的:Fragment
Activity
Fragment
public static void hideKeyboardFrom(Context context, View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
以下是从追逐此解决方案所浪费的更多时间中收集到的一些附加信息:
关于windowSoftInputMode
还有另一个争论点需要注意。默认情况下,Android 会自动将初始焦点分配给 .自然而然地,InputMethod(通常是软键盘)将通过显示自身来响应焦点事件。当 中的属性设置为 时,指示键盘忽略此自动分配的初始焦点。EditText
Activity
windowSoftInputMode
AndroidManifest.xml
stateAlwaysHidden
<activity
android:name=".MyActivity"
android:windowSoftInputMode="stateAlwaysHidden"/>
几乎令人难以置信的是,当您触摸控件时,它似乎没有执行任何操作来阻止键盘打开(除非和/或分配给控件)。显然,windowSoftInputMode 设置仅适用于自动焦点事件,而不适用于由触摸事件触发的焦点事件。focusable="false"
focusableInTouchMode="false"
因此,确实命名得很差。也许应该改用它。stateAlwaysHidden
ignoreInitialFocus
更新:获取窗口令牌的更多方法
如果没有聚焦视图(例如,如果您刚刚更改了片段,则可能会发生这种情况),则其他视图将提供有用的窗口令牌。
这些是上述代码的替代方法:这些代码不明确引用您的活动。if (view == null) view = new View(activity);
在 fragment 类中:
view = getView().getRootView().getWindowToken();
给定一个片段作为参数:fragment
view = fragment.getView().getRootView().getWindowToken();
从内容正文开始:
view = findViewById(android.R.id.content).getRootView().getWindowToken();
更新2:清除焦点以避免在从后台打开应用程序时再次显示键盘
将以下行添加到方法的末尾:
view.clearFocus();
评论
getRootView()
getView()
((InputMethodManager)getContext().getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getView().getWindowToken(), 0);
使用这个
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
或者,如果您想从任何位置关闭软键盘,而不引用用于打开键盘的 (EditText) 字段,但仍希望在该字段处于焦点状态时执行此操作,则可以使用此(来自 Activity):
if (getCurrentFocus() != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
这应该有效:
public class KeyBoard {
public static void show(Activity activity){
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
}
public static void hide(Activity activity){
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
}
public static void toggle(Activity activity){
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm.isActive()){
hide(activity);
} else {
show(activity);
}
}
}
KeyBoard.toggle(activity);
评论
KeyBoard.toggle(fragment.getActivity())
Fragment
这种方法将始终不惜一切代价起作用。只需在您想隐藏键盘的任何地方使用它
public static void hideSoftKeyboard(Context mContext,EditText username){
if(((Activity) mContext).getCurrentFocus()!=null && ((Activity) mContext).getCurrentFocus() instanceof EditText){
InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(username.getWindowToken(), 0);
}
}
像这样使用它:
无论Android的版本是什么。这种方法肯定会奏效
这对我有用:
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (v instanceof EditText) {
View w = getCurrentFocus();
int scrcoords[] = new int[2];
w.getLocationOnScreen(scrcoords);
float x = event.getRawX() + w.getLeft() - scrcoords[0];
float y = event.getRawY() + w.getTop() - scrcoords[1];
Log.d("Activity",
"Touch event " + event.getRawX() + "," + event.getRawY()
+ " " + x + "," + y + " rect " + w.getLeft() + ","
+ w.getTop() + "," + w.getRight() + ","
+ w.getBottom() + " coords " + scrcoords[0] + ","
+ scrcoords[1]);
if (event.getAction() == MotionEvent.ACTION_UP
&& (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w
.getBottom())) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus()
.getWindowToken(), 0);
}
}
return ret;
}
它对我有用..
EditText editText=(EditText)findViewById(R.id.edittext1);
将 onClick() 中的代码行放在下面
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
当我们单击按钮时,这里隐藏键盘,当我们触摸 EditText 键盘将显示。
(或)
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
这对我所有奇怪的键盘行为都有效
private boolean isKeyboardVisible() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
mRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = mRootView.getRootView().getHeight() - (r.bottom - r.top);
return heightDiff > 100; // if more than 100 pixels, its probably a keyboard...
}
protected void showKeyboard() {
if (isKeyboardVisible())
return;
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (getCurrentFocus() == null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
} else {
View view = getCurrentFocus();
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
}
}
protected void hideKeyboard() {
if (!isKeyboardVisible())
return;
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View view = getCurrentFocus();
if (view == null) {
if (inputMethodManager.isAcceptingText())
inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0);
} else {
if (view instanceof EditText)
((EditText) view).setText(((EditText) view).getText().toString()); // reset edit text bug on some keyboards bug
inputMethodManager.hideSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
评论
public static void closeInput(final View caller) {
caller.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) caller.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(caller.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 100);
}
此方法通常有效,但有一个条件:您不能设置android:windowSoftInputMode="any_of_these"
这对我有用。
public static void hideKeyboard(Activity act, EditText et){
Context c = act.getBaseContext();
View v = et.findFocus();
if(v == null)
return;
InputMethodManager inputManager = (InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
只需在 Activity 中使用此优化的代码:
if (this.getCurrentFocus() != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
另一种方法是使用以下代码:SearchView
searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
InputMethodManager imm = (InputMethodManager)
getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getApplicationWindowToken(), 0);
}
}
这是 ActionBar 中的一个 SearchView 搜索框,当提交查询中的文本(用户按任一键或搜索按钮/图标)时,代码将被激活并使软键盘关闭。这段代码被放在我的. 是 的默认代码的一部分。感谢 @mckoss 提供了大量代码!Enter
InputMethodManager
onCreateOptionsMenu()
searchItem
MenuItem
onCreateOptionsmenu()
简短的回答
在侦听器中调用OnClick
onEditorAction
EditText
IME_ACTION_DONE
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
someEditText.onEditorAction(EditorInfo.IME_ACTION_DONE)
}
});
向下钻取
我觉得这种方法更好、更简单,更符合 Android 的设计模式。
在上面的简单示例中(通常在大多数常见情况下),您将有一个具有/具有焦点的键盘,并且它通常也是首先调用键盘的那个(在许多常见情况下,它绝对能够调用它)。同样,它应该是释放键盘的那个,通常可以通过 .看看 with 的行为,你想用同样的方式实现同样的行为。EditText
ImeAction
EditText
android:imeOptions="actionDone"
查看此相关答案
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity
.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
.getWindowToken(), 0);
}
评论
activity.getCurrentFocus()
null
private void hideSoftKeyboard() {
View view = getView();
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
抛开所有这些答案,为了简单起见,我写了一个常用的方法来做到这一点:
/**
* hide soft keyboard in a activity
* @param activity
*/
public static void hideKeyboard (Activity activity){
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
if (activity.getCurrentFocus() != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}
我有这种情况,我的也可以位于 ,所以键盘应该在关闭时关闭。以下代码似乎在任何地方都可以使用:EditText
AlertDialog
public static void hideKeyboard( Activity activity ) {
InputMethodManager imm = (InputMethodManager)activity.getSystemService( Context.INPUT_METHOD_SERVICE );
View f = activity.getCurrentFocus();
if( null != f && null != f.getWindowToken() && EditText.class.isAssignableFrom( f.getClass() ) )
imm.hideSoftInputFromWindow( f.getWindowToken(), 0 );
else
activity.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN );
}
评论
试试这个
public void disableSoftKeyboard(final EditText v) {
if (Build.VERSION.SDK_INT >= 11) {
v.setRawInputType(InputType.TYPE_CLASS_TEXT);
v.setTextIsSelectable(true);
} else {
v.setRawInputType(InputType.TYPE_NULL);
v.setFocusable(true);
}
}
对于打开键盘:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edtView, InputMethodManager.SHOW_IMPLICIT);
对于关闭/隐藏键盘:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edtView.getWindowToken(), 0);
我已经尝试了所有解决方案,但没有解决方案适合我,所以我找到了我的解决方案: 你应该有布尔变量,如:
public static isKeyboardShowing = false;
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
在触摸屏事件中,您调用:
@Override
public boolean onTouchEvent(MotionEvent event) {
if(keyboardShowing==true){
inputMethodManager.toggleSoftInput(InputMethodManager.RESULT_UNCHANGED_HIDDEN, 0);
keyboardShowing = false;
}
return super.onTouchEvent(event);
}
在 EditText 中,在任何地方:
yourEditText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
yourClass.keyboardShowing = true;
}
});
我几乎尝试了所有这些答案,我遇到了一些随机问题,尤其是三星Galaxy s5。
我最终得到的是强制显示和隐藏,它运行良好:
/**
* Force show softKeyboard.
*/
public static void forceShow(@NonNull Context context) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
/**
* Force hide softKeyboard.
*/
public static void forceHide(@NonNull Activity activity, @NonNull EditText editText) {
if (activity.getCurrentFocus() == null || !(activity.getCurrentFocus() instanceof EditText)) {
editText.requestFocus();
}
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
public void setKeyboardVisibility(boolean show) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(show){
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}else{
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
}
}
多亏了这个 SO 答案,我得出了以下内容,就我而言,在滚动浏览 ViewPager 的片段时效果很好......
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
private void showKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
}
有时,您可以有一个包含列表视图的活动,其中包含包含 editText 的行,因此您必须在清单中进行设置,然后它们会出现键盘,这很烦人。SOFT_INPUT_ADJUST_PAN
如果您将以下工作圈放在onCreate
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
},100);
在设置下AndroidManifest.xml
<activity..>
android:windowSoftInputMode="stateAlwaysHidden"
简单代码: 在 onCreate() 中使用此代码
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
在某些情况下,除了所有其他方法外,此方法可以起作用。 这节省了我的一天:)
public static void hideSoftKeyboard(Activity activity) {
if (activity != null) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null && inputManager != null) {
inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
inputManager.hideSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
}
}
}
public static void hideSoftKeyboard(View view) {
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager != null) {
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
添加到清单文件中的活动。例:android:windowSoftInputMode="stateHidden"
<activity
android:name=".ui.activity.MainActivity"
android:label="@string/mainactivity"
android:windowSoftInputMode="stateHidden"/>
/**
*
* Hide I Said!!!
*
*/
public static boolean hideSoftKeyboard(@NonNull Activity activity) {
View currentFocus = activity.getCurrentFocus();
if (currentFocus == null) {
currentFocus = activity.getWindow().getDecorView();
if (currentFocus != null) {
return getSoftInput(activity).hideSoftInputFromWindow(currentFocus.getWindowToken(), 0, null);
}
}
return false;
}
public static boolean hideSoftKeyboard(@NonNull Context context) {
if(Activity.class.isAssignableFrom(context.getClass())){
return hideSoftKeyboard((Activity)context);
}
return false;
}
public static InputMethodManager getSoftInput(@NonNull Context context) {
return (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
}
简单的方法伙计们: 试试这个...
private void closeKeyboard(boolean b) {
View view = this.getCurrentFocus();
if(b) {
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
else {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, 0);
}
}
如果您想使用 Java 代码隐藏键盘,请使用以下命令:
InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(fEmail.getWindowToken(), 0);
或者,如果您想始终隐藏键盘,请在 AndroidManifest 中使用它:
<activity
android:name=".activities.MyActivity"
android:configChanges="keyboardHidden" />
评论
用try catch包围它,这样键盘已经关闭,应用程序不会崩溃:
try{
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}catch (Exception e)
{
e.printStackTrace();
}
您只需在清单活动标记中写入一行
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"
它会起作用的。
简单易用的方法,只需调用hideKeyboardFrom(YourActivity.this)即可隐藏键盘
/**
* This method is used to hide keyboard
* @param activity
*/
public static void hideKeyboardFrom(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
评论
activity.getCurrentFocus()
final RelativeLayout llLogin = (RelativeLayout) findViewById(R.id.rl_main);
llLogin.setOnTouchListener(
new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent ev) {
InputMethodManager imm = (InputMethodManager) this.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
return false;
}
});
每次都像魔术一样工作
private void closeKeyboard() {
InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
private void openKeyboard() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
}
在阅读了上面和另一篇文章中的所有答案后,我仍然没有成功让键盘自动打开。
在我的项目中,我动态地创建了一个对话框(通过在不使用或使用最少的 XML 的情况下对其进行编程)。AlertDialog
所以我在做这样的事情:
dialogBuilder = new AlertDialog.Builder(activity);
if(dialogBuilder==null)
return false; //error
inflater = activity.getLayoutInflater();
dialogView = inflater.inflate(layout, null);
...
在完成所有视图(TextView、ImageView、EditText 等)的设置后。我做了:
alertDialog = dialogBuilder.create();
alertDialog.show();
在玩弄了所有答案之后,我发现如果您知道在哪里提出请求,它们中的大多数都有效......这是所有事情的关键。
所以,诀窍是把它放在创建对话框之前:就我而言,这就像魅力一样:alertDialog.show()
alertDialog = dialogBuilder.create();
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//And only when everything is finished - let's bring up the window -
alertDialog.show();
//Viola... keyboard is waiting for you open and ready...
//Just don't forget to request focus for the needed view (i.e. EditText..)
我很确定这个原则对所有窗口都是相同的,所以要注意你的“showKeyboard”代码的位置 - 它应该在窗口启动之前。
来自 Android SDK 开发团队的一个小请求:
我认为这一切都是不必要的,因为你可以看到来自世界各地的成千上万的程序员正在处理这个荒谬而琐碎的问题,而它的解决方案应该是干净和简单的:
恕我直言,如果我进入面向输入的视图(例如),键盘应该会自动打开,除非用户要求不要打开,所以,我认为 requestFocus() 方法是这里的关键,应该接受默认值为的布尔值 showSoftKeyboard:requestFocus()
EditText
true
View.requestFocus(boolean showSoftKeyboard);
希望这能帮助到像我这样的人。
试试这个
- 简单,你可以调用你的
Activity
public static void hideKeyboardwithoutPopulate(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(), 0);
}
- 在你的电话中,这个
MainActivitiy
hideKeyboardwithoutPopulate(MainActivity.this);
这是工作..
只需在函数中传递当前活动实例
public void isKeyBoardShow(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
} else {
imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
}
}
Kotlin 版本
val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
评论
Activity
fun Activity.closeKeyboard() { (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).apply { hideSoftInputFromWindow(window.decorView.windowToken, 0) } }
你可以简单地将此代码添加到你想隐藏软键盘的位置。
// Check if no view has focus:
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
这是最好的解决方案
解决方案 1) 将 inputType 设置为“text”
<EditText
android:id="@+id/my_edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Tap here to type"
android:inputType="text" />
这也可以通过以下方式以编程方式完成。setInputType() 方法(继承自 TextView)。
EditText editText = (EditText) findViewById(R.id.my_edit_text);
editText.setRawInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_NORMAL);
解决方案 2) 使用 InputMethodManager.hideSoftInputFromWindow()
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
或
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
如果有人有兴趣,我已经为 Kotlin 编写了小扩展,但没有对其进行太多测试:
fun Fragment.hideKeyboard(context: Context = App.instance) {
val windowToken = view?.rootView?.windowToken
windowToken?.let {
val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
}
App.instance 是存储在 Application 中的静态“this”Application 对象
更新:在某些情况下,windowToken 为 null。我添加了使用反射关闭键盘的附加方法,以检测键盘是否关闭
/**
* If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
*
* @param useReflection - whether to use reflection in case of no window token or not
*/
fun Fragment.hideKeyboard(context: Context = MainApp.instance, useReflection: Boolean = true) {
val windowToken = view?.rootView?.windowToken
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
windowToken?.let {
imm.hideSoftInputFromWindow(windowToken, 0)
} ?: run {
if (useReflection) {
try {
if (getKeyboardHeight(imm) > 0) {
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
}
} catch (exception: Exception) {
Timber.e(exception)
}
}
}
}
fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int
在 Android 中,要通过 InputMethodManage 隐藏 Vkeyboard,可以通过传入包含焦点视图的窗口的令牌来 cal hideSoftInputFromWindow。
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager im =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
通过调用 editText.clearFocus(),然后InputMethodManager.HIDE_IMPLICIT_ONLY甚至可以工作
如果应用程序面向 API 级别 21 或更高级别,则使用默认方法:
editTextObj.setShowSoftInputOnFocus(false);
确保您已在 XML 标记中设置了以下代码。EditText
<EditText
....
android:enabled="true"
android:focusable="true" />
一些 kotlin 代码:
在“活动”中隐藏键盘:
(currentFocus ?: View(this))
.apply { (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(windowToken, 0) }
非常简单的方法
我在我所有的项目中都是这样做的,并且像做梦一样工作。在您的声明中,只需添加以下一行:layout.xml
android:focusableInTouchMode="true"
完整代码示例:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</android.support.constraint.ConstraintLayout>
您可以为任何视图创建扩展函数
fun View.hideKeyboard() = this.let {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
与 Activity 一起使用的示例
window.decorView.hideKeyboard();
与 View 一起使用的示例
etUsername.hideKeyboard();
祝您编码愉快...
实际上,Android 权威总是提供新的更新,但他们没有处理所有 Android 开发人员在开发中面临的旧缺点,默认情况下,这应该由 Android 权威处理,在从 EditText 更改焦点时,应该隐藏/显示软输入键盘选项。但很抱歉,他们没有管理。好吧,离开它。
以下是在 Activity 或 Fragment 中显示/隐藏/切换键盘选项的解决方案。
显示视图的键盘:
/**
* open soft keyboard.
*
* @param context
* @param view
*/
public static void showKeyBoard(Context context, View view) {
try {
InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(view, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
显示具有活动上下文的键盘:
/**
* open soft keyboard.
*
* @param mActivity context
*/
public static void showKeyBoard(Activity mActivity) {
try {
View view = mActivity.getCurrentFocus();
if (view != null) {
InputMethodManager keyboard = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.SHOW_FORCED);
}
} catch (Exception e) {
e.printStackTrace();
}
}
使用 Fragment 上下文显示键盘:
/**
* open soft keyboard.
*
* @param mFragment context
*/
public static void showKeyBoard(Fragment mFragment) {
try {
if (mFragment == null || mFragment.getActivity() == null) {
return;
}
View view = mFragment.getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager keyboard = (InputMethodManager) mFragment.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.SHOW_FORCED);
}
} catch (Exception e) {
e.printStackTrace();
}
}
隐藏视图的键盘:
/**
* close soft keyboard.
*
* @param context
* @param view
*/
public static void hideKeyBoard(Context context, View view) {
try {
InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.hideSoftInputFromWindow(view.getWindowToken(), 0);
} catch (Exception e) {
e.printStackTrace();
}
}
隐藏具有活动上下文的键盘:
/**
* close opened soft keyboard.
*
* @param mActivity context
*/
public static void hideSoftKeyboard(Activity mActivity) {
try {
View view = mActivity.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
使用 Fragment 上下文隐藏键盘:
/**
* close opened soft keyboard.
*
* @param mFragment context
*/
public static void hideSoftKeyboard(Fragment mFragment) {
try {
if (mFragment == null || mFragment.getActivity() == null) {
return;
}
View view = mFragment.getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) mFragment.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
切换键盘:
/**
* toggle soft keyboard.
*
* @param context
*/
public static void toggleSoftKeyboard(Context context) {
try {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
在 Kotlin 中
fun hideKeyboard(activity: BaseActivity) {
val view = activity.currentFocus?: View(activity)
val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
我正在使用以下 Kotlin Activity 扩展:
/**
* Hides soft keyboard if is open.
*/
fun Activity.hideKeyboard() {
currentFocus?.windowToken?.let {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
?.hideSoftInputFromWindow(it, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
/**
* Shows soft keyboard and request focus to given view.
*/
fun Activity.showKeyboard(view: View) {
view.requestFocus()
currentFocus?.windowToken?.let {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
当您想在按钮单击操作时手动隐藏键盘时:
/**
* Hides the already popped up keyboard from the screen.
*
*/
public void hideKeyboard() {
try {
// use application level context to avoid unnecessary leaks.
InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
assert inputManager != null;
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
e.printStackTrace();
}
}
当您想在单击屏幕时隐藏键盘时,编辑文本除外在 Activity 中覆盖此方法:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
View view = getCurrentFocus();
if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
int scrcoords[] = new int[2];
view.getLocationOnScreen(scrcoords);
float x = ev.getRawX() + view.getLeft() - scrcoords[0];
float y = ev.getRawY() + view.getTop() - scrcoords[1];
if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
}
return super.dispatchTouchEvent(ev);
}
要在应用程序启动时显示键盘:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
view.requestFocus();
new Handler().postDelayed(new Runnable() {
public void run() {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
}
}, 1000);
对于 Xamarin.Android:
public void HideKeyboard()
{
var imm = activity.GetSystemService(Context.InputMethodService).JavaCast<InputMethodManager>();
var view = activity.CurrentFocus ?? new View(activity);
imm.HideSoftInputFromWindow(view.WindowToken, HideSoftInputFlags.None);
}
这里有隐藏和显示方法。
Kotlin
fun hideKeyboard(activity: Activity) {
val v = activity.currentFocus
val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
assert(v != null)
imm.hideSoftInputFromWindow(v!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
private fun showKeyboard(activity: Activity) {
val v = activity.currentFocus
val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
assert(v != null)
imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT)
}
爪哇岛
public static void hideKeyboard(Activity activity) {
View v = activity.getCurrentFocus();
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null && v != null;
imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
private static void showKeyboard(Activity activity) {
View v = activity.getCurrentFocus();
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null && v != null;
imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
}
在 Kotlin 中试试这个
private fun hideKeyboard(){
val imm = activity!!.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(activity!!.currentFocus!!.windowToken, 0)
}
在 Java 中尝试此操作
private void hideKeyboard(){
InputMethodManager imm =(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
fun hideKeyboard(appCompatActivity: AppCompatActivity) {
val view = appCompatActivity.currentFocus
val imm = appCompatActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
public void hideKeyboard()
{
if(getCurrentFocus()!=null)
{
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
public void showKeyboard(View mView) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
mView.requestFocus();
inputMethodManager.showSoftInput(mView, 0);
}
Kotlin 中的 Wiki 答案:
1 - 在文件(例如,包含所有顶级函数的文件)内创建一个顶级函数:
fun Activity.hideKeyboard(){
val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
var view = currentFocus
if (view == null) { view = View(this) }
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
2 - 然后在您需要的任何活动中调用它:
this.hideKeyboard()
调用此方法隐藏软键盘
public void hideKeyBoard() {
View view1 = this.getCurrentFocus();
if(view!= null){
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view1.getWindowToken(), 0);
}
}
对于 kotlin 用户,这里有一个适用于我的用例的 kotlin 扩展方法:
fun View.hideKeyboard() {
val imm = this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
把它放在一个名为 ViewExtensions(或你有什么)的文件中,并像普通方法一样在您的视图上调用它。
如果您使用 Kotlin 来开发应用程序,这真的很容易做到。
添加以下扩展功能:
对于活动:
fun Activity.hideKeyboard() {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val view = currentFocus
if (view != null) {
inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
对于 Fragment:
fun Fragment.hideKeyboard() {
activity?.let {
val inputManager = it.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val view = it.currentFocus
if (view != null) {
inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
}
现在,您可以简单地调用 Fragment 或 Activity:
hideKeyboard()
评论
嗨,这很简单,如果您正在使用 Kotlin,那么您也可以轻松地将代码转换为 Java 首先在您的活动中,在加载活动时使用此函数,例如在 onCreate() 中调用它。
fun hideKeybord (){
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (inputManager.isAcceptingText){
inputManager.hideSoftInputFromWindow(currentFocus.windowToken, 0)
}
}
正如我提到的,在您的 onCreate() 方法中调用此函数,然后将此行添加到您在 manafest.xml 文件中的活动,如下所示...android:windowSoftInputMode="stateAlwaysHidden"
<activity
android:name=".Activity.MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar"
android:windowSoftInputMode="stateAlwaysHidden">
there are two ways to do so...
method 1:in manifest file
define the line **android:windowSoftInputMode="adjustPan|stateAlwaysHidden"** of code in your manifest.xml file as below...
<activity
android:name="packagename.youactivityname"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|stateAlwaysHidden" />
Method 2 : in Activity or Java class
if(getCurrentFocus()!=null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)`enter code here`;
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
它会work....@ASK
下面的代码将帮助您制作可以从任何地方调用的泛型函数。
import android.app.Activity
import android.content.Context
import android.support.design.widget.Snackbar
import android.view.View
import android.view.inputmethod.InputMethodManager
public class KeyboardHider {
companion object {
fun hideKeyboard(view: View, context: Context) {
val inputMethodManager = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
}
}
使用一行代码从任意位置调用 Above 方法。
CustomSnackbar.hideKeyboard(view, this@ActivityName)
视图可以是任何内容,例如活动的根布局。
评论
只需在 BaseActivity 和 BaseFragment 中为整个应用程序制定通用方法
在初始化中onCreate()
inputMethodManager
inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
使此方法隐藏和显示键盘
public void hideKeyBoard(View view) {
if (view != null) {
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public void showKeyboard(View view, boolean isForceToShow) {
if (isForceToShow)
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
else if (view != null)
inputMethodManager.showSoftInput(view, 0);
}
此代码片段可以提供帮助:
final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
if (inputMethodManager != null && inputMethodManager.isActive()) {
if (getCurrentFocus() != null) {
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
它可以根据需要以不同的方法调用(例如onPause,onResume,onRestart...
首先,您应该从 XML 文件中添加 android:imeOptions 字段,并将其值更改为 actionUnspecified|actionGo,如下所示
<android.support.design.widget.TextInputEditText
android:id="@+id/edit_text_id"
android:layout_width="fill_parent"
android:layout_height="@dimen/edit_text_height"
android:imeOptions="actionUnspecified|actionGo"
/>
然后在 java 类中添加一个 setOnEditorActionListener 并添加 InputMethodManager,如下所示
enterOrderNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
return true;
}
return false;
}
});
这对我来说是工作。它在 Kotlin 中用于隐藏键盘。
private fun hideKeyboard() {
val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val focusedView = activity?.currentFocus
if (focusedView != null) {
inputManager.hideSoftInputFromWindow(focusedView.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS)
}
}
只需在特定 Activity 的 AndroidManifest 中添加以下行即可。
<activity
android:name=".MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan"/>
一个简单的解决方法是只使用 Button 方法。editText.setEnabled(false);editText.setEnabled(true);
onClick()
试试这个:
完全强制使用Android软输入键盘:
在帮助器类中创建方法
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
我使用 Kotlin 扩展来显示和隐藏键盘。
fun View.showKeyboard() {
this.requestFocus()
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
这适用于Android 10 (API 29)的片段:
val activityView = activity?.window?.decorView?.rootView
activityView?.let {
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(it.windowToken, 0)
}
评论
一个简单的方法是在 EditText 视图中设置以下属性。
android:imeOptions="actionDone"
适合 Kotlin 爱好者。我创建了两个扩展函数。为了获得 hideKeyboard 的乐趣,您可以将 edittext 的实例作为视图传递。
fun Context.hideKeyboard(view: View) {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
hideSoftInputFromWindow(view.windowToken, 0)
}
}
fun Context.showKeyboard() {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
}
只需在视图中添加此属性即可隐藏键盘。EditTect
android:focusable="false"
评论
只需调用以下方法即可。如果它显示,它将隐藏您的键盘。
public void hideKeyboard() {
try {
InputMethodManager inputmanager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputmanager != null) {
inputmanager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
}
}
catch (Exception var2) {
}
}
通过将泛型方法添加到实用程序或帮助程序类中。只需调用自身,即可隐藏和显示键盘:
fun AppCompatActivity.hideKeyboard() {
val view = this.currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}
fun AppCompatActivity.showKeyboard() {
val view = this.currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}
您也可以使用此代码片段在 Kotlin 中隐藏键盘。
fun hideKeyboard(activity: Activity?) {
val inputManager: InputMethodManager? =
activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as?
InputMethodManager
// Check if no view has focus:
val v = activity?.currentFocus ?: return
inputManager?.hideSoftInputFromWindow(v.windowToken, 0)
}
从一个片段移动到另一个片段时
fun hideKeyboard(activity: Activity?): Boolean {
val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
if (inputManager != null) {
val currentFocus = activity?.currentFocus
if (currentFocus != null) {
val windowToken = currentFocus.windowToken
if (windowToken != null) {
return inputManager.hideSoftInputFromWindow(windowToken, 0)
}
}
}
return false
}
fun showKeyboard(editText: EditText) {
val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(editText.windowToken, 0)
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)
editText.requestFocus()
}
评论
通过扩展功能的 Kotlin 版本
使用 Kotlin 扩展功能,显示和隐藏软键盘将非常简单。
扩展函数.kt
import android.app.Activity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.fragment.app.Fragment
fun Activity.hideKeyboard(): Boolean {
return (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow((currentFocus ?: View(this)).windowToken, 0)
}
fun Fragment.hideKeyboard(): Boolean {
return (context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow((activity?.currentFocus ?: View(context)).windowToken, 0)
}
fun EditText.hideKeyboard(): Boolean {
return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(windowToken, 0)
}
fun EditText.showKeyboard(): Boolean {
return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
.showSoftInput(this, 0)
}
用法
现在在 ur or 中,可以清楚地访问它,也可以从以下实例中调用它:Activity
Fragment
hideKeyboard()
EditText
editText.hideKeyboard()
Kotlin
class KeyboardUtils{
companion object{
fun hideKeyboard(activity: Activity) {
val imm: InputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
var view: View? = activity.currentFocus
if (view == null) {
view = View(activity)
}
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
}
然后只需在您需要的地方调用它
碎片
KeyboardUtils.hideKeyboard(requireActivity())
活动
KeyboardUtils.hideKeyboard(this)
使用 Android 10,我们将获得一种显示和隐藏键盘的惊人方式。阅读发行说明 - 1.5.0-alpha02。现在如何隐藏或显示键盘:
val controller = view.windowInsetsController
// Show the keyboard
controller.show(Type.ime())
// Hide the keyboard
controller.hide(Type.ime())
链接我自己的答案 如何在Android中检查软件键盘的可见性? 以及一个惊人的博客,其中包含更多这种变化(甚至比它更多)。
评论
Type
Android 11 中有一个名为 .应用程序可以从任何视图访问控制器,通过该视图,我们可以使用 和 方法:WindowInsetsController
hide()
show()
val controller = view.windowInsetsController
// Show the keyboard (IME)
controller.show(Type.ime())
// Hide the keyboard
controller.hide(Type.ime())
//In Activity
View v = this.getCurrentFocus();
if (v != null) {
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
//In Fragment
View v = getActivity().getCurrentFocus();
if (v != null) {
InputMethodManager im = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
```
这个对我有用。你只需要在里面传递元素。
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(AutocompleteviewDoctorState.getWindowToken(), 0);
如果你在android:focused=“true”中设置,那么它将不起作用,因为它是一个不可更改的集合。.xml
所以解决方案:
android:focusedByDefault=“true”
然后它会设置一次,可以隐藏或显示键盘。
片段中的 Kotlin 解决方案
fun hideSoftKeyboard() {
val view = activity?.currentFocus
view?.let { v ->
val imm =
activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager // or context
imm.hideSoftInputFromWindow(v.windowToken, 0)
}
}
检查清单中是否没有与活动关联的此参数:
android:windowSoftInputMode="stateAlwaysHidden"
有很多答案。如果毕竟没有任何效果,那么这里有一个提示:),
您可以制作一个 EditText 和
edittext.setAlpha(0f);
由于 alpha 方法,将看不到此 edittext。 现在使用上面关于如何使用 EditText 显示/隐藏软键盘的答案。
如果您需要在片段中隐藏键盘,此方法有效。
public static void hideSoftKeyboard(Context context, View view) {
if (context != null && view != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
对于视图,只需传入
getView() method
在 Kotlin 中,只需使用这两种方法来显示和隐藏键盘。
fun showKeyboard() =
(context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as? InputMethodManager)!!
.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
fun hideKeyboard(view: View) =
(context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as? InputMethodManager)!!
.hideSoftInputFromWindow(view.windowToken, 0)
这是您当前的观点。view
以下是使用 Kotlin 隐藏软键盘的最简单方法:
//hides soft keyboard anything else is tapped( screen, menu bar, buttons, etc. )
override fun dispatchTouchEvent( ev: MotionEvent? ): Boolean {
if ( currentFocus != null ) {
val imm = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
imm.hideSoftInputFromWindow( currentFocus!!.windowToken, 0 )
}
return super.dispatchTouchEvent( ev )
}
现在,差不多 12 年后,我们终于有一种官方的、向后兼容的方式来与 AndroidX Core 1.5+ 做到这一点:
fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)
?.hide(WindowInsetsCompat.Type.ime())
或专门针对 Fragment:
fun Fragment.hideKeyboard() = ViewCompat.getWindowInsetsController(requireView())
?.hide(WindowInsetsCompat.Type.ime())
评论
window.decorView
currentFocus?.windowToken
InputMethodManager.hideSoftInputFromWindow(windowToken, 0)
window.decorView
ViewCompat.getWindowInsetsController()
null
currentFocus
EditText
WindowInsetsControllerCompat.show()
currentFocus
window.decorView
SomeBinding.root
Fragment
view?.hideKeyboard()
context.getSystemService<InputMethodManager>()?.hideSoftInputFromWindow(windowToken, 0)
别忘了:在智能手机的系统设置中,处于“输入法和语言”->物理键盘->显示屏幕键盘->开/关”。此设置“干扰”了此处的所有编程解决方案!我也不得不禁用/启用此设置才能完全隐藏/显示屏幕键盘!因为我正在为设备 MC2200 开发,所以我使用“EMDK 配置文件管理 -> UI 管理器 -> 虚拟键盘状态 -> 显示/隐藏”来完成
感谢上帝,它在 11 年后得到了官方支持。
首先,将依赖项添加到应用 gradle。implementation 'androidx.core:core-ktx:1.7.0'
然后从 ViewCompat 或 WindowCompat 类获取 InsetsController。
最后使用 InsetsController 的 hide() 和 show() 函数
添加对 Dialog 的支持。在 BottomSheetDialog 中可用。@Rondev。 使用更安全的方式获取活动,而不是直接从上下文中强制转换。
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
fun View.showKeyboard() = ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)?.hide(WindowInsetsCompat.Type.ime())
fun Dialog.showKeyboard() = window?.decorView?.showKeyboard()
fun Dialog.hideKeyboard() = window?.decorView?.hideKeyboard()
fun Context.showKeyboard() = getActivity()?.showKeyboard()
fun Context.hideKeyboard() = getActivity()?.hideKeyboard()
fun Fragment.showKeyboard() = activity?.showKeyboard()
fun Fragment.hideKeyboard() = activity?.hideKeyboard()
fun Activity.showKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.show(WindowInsetsCompat.Type.ime())
fun Activity.hideKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.hide(WindowInsetsCompat.Type.ime())
fun Context.getActivity(): Activity? {
return when (this) {
is Activity -> this
is ContextWrapper -> this.baseContext.getActivity()
else -> null
}
}
下面的旧 anwser
这是github上的简单项目
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
fun View.showKeyboard() = ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)?.hide(WindowInsetsCompat.Type.ime())
fun Dialog.showKeyboard() = window?.decorView?.showKeyboard()
fun Dialog.hideKeyboard() = window?.decorView?.hideKeyboard()
fun Context.showKeyboard() = getActivity()?.showKeyboard()
fun Context.hideKeyboard() = getActivity()?.hideKeyboard()
fun Fragment.showKeyboard() = activity?.showKeyboard()
fun Fragment.hideKeyboard() = activity?.hideKeyboard()
fun Activity.showKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.show(WindowInsetsCompat.Type.ime())
fun Activity.hideKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.hide(WindowInsetsCompat.Type.ime())
fun Context.getActivity(): Activity? {
return when (this) {
is Activity -> this
is ContextWrapper -> this.baseContext.getActivity()
else -> null
}
}
评论
BottomSheetDialogFragment
public final class UtilsKeyboard {
/**
* Sets the cursor at the end of this edit text and shows a keyboard
*/
public static void focusKeyboard(@NonNull EditText editText) {
editText.requestFocus();
editText.setSelection(editText.getText().length());
showKeyboard(editText);
}
private static void showKeyboard(@NonNull View view) {
final InputMethodManager manager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (manager != null) {
manager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
}
}
public static boolean hideKeyboard(@NonNull Window window) {
View view = window.getCurrentFocus();
return hideKeyboard(window, view);
}
private static boolean hideKeyboard(@NonNull Window window, @Nullable View view) {
if (view == null) {
return false;
}
InputMethodManager inputMethodManager = (InputMethodManager) window.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
return inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
return false;
}
public static boolean hideKeyboard(@Nullable View view) {
if (view == null) {
return false;
}
InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
return inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
return false;
}
/**
* This will hide the keyboard and unfocus any focused view.
*/
public static void unfocusKeyboard(@NonNull Window window) {
// When showing the bottom menu, make sure the keyboard isn't and that no view has focus
hideKeyboard(window);
final View focused = window.getCurrentFocus();
if (focused != null) focused.clearFocus();
}}
通过创建可全局使用的扩展程序,在 Kotlin 中隐藏软键盘。为此,您需要创建一个 Singleton 类。
object Extensions {
fun View.hideKeyboard() {
val inputMethodManager =
context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE)
as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
}
在需要隐藏键盘的 fragment 类的活动中,可以使用 mainlayout id 调用此函数,如下所示
//constraintEditLayout is my main view layout, if you are using other layout like relative or linear layouts you can call with that layout id
constraintEditLayout.hideKeyboard()
这对我有用
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive())
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
此代码将帮助您在触摸编辑文本外部或其他任何地方时隐藏键盘。您需要在 Activity 中添加此代码,或者您可以在项目的父 Activity 中编写代码,它还会在 webview 中隐藏您的键盘。
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
View v = getCurrentFocus();
if (v != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && v instanceof EditText &&
!v.getClass().getName().startsWith("android.webkit.")) {
int[] sourceCoordinates = new int[2];
v.getLocationOnScreen(sourceCoordinates);
float x = ev.getRawX() + v.getLeft() - sourceCoordinates[0];
float y = ev.getRawY() + v.getTop() - sourceCoordinates[1];
if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) {
hideKeyboard(this);
}
}
return super.dispatchTouchEvent(ev);
}
private void hideKeyboard(Activity activity) {
if (activity != null && activity.getWindow() != null) {
activity.getWindow().getDecorView();
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
}
}
}
public static void hideKeyboard(View view) {
if (view != null) {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
我的解决方案:
使用活动构造它(视图是可选的),使用处理程序来发布它(有一些延迟,例如,100 毫秒更好)。 直接调用输入管理器有时是行不通的。 它只有在我们可以获得 Activity 时才有效。我认为这很正常。
如果可以在调用时获取根视图组或编辑视图。只需将其发送即可获得更好的结果。
public class CloseSoftKeyboardRunnable implements Runnable
{
Activity activity;
View view; // For dialog will occur context getcurrentfocus == null. send a rootview to find currentfocus.
public CloseSoftKeyboardRunnable(Activity activity, View view)
{
this.activity = activity;
this.view = view;
}
public CloseSoftKeyboardRunnable(Activity activity)
{
this.activity = activity;
}
@Override
public void run() {
if (!activity.isFinishing())
{
InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (view == null) {
view = activity.getCurrentFocus();
}
else
{
try {
view = ((ViewGroup)view).getFocusedChild();
}
catch ( Exception e) {}
}
Window window = activity.getWindow();
if (window != null)
{
if (view == null) {
try {
view = window.getDecorView();
view = ((ViewGroup)view).getFocusedChild();
}
catch ( Exception e) {}
}
if (view == null) {
view = window.getDecorView();
}
if (view != null) {
if (view instanceof EditText)
{
EditText edittext = ((EditText) view);
edittext.setText(edittext.getText().toString()); // Reset edit text bug on some keyboards bug
edittext.clearFocus();
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
}
}
这些答案中有许多是不必要的复杂;这是 Kotlin 用户在类上创建一个简洁的小扩展函数的解决方案。View
创建一个基本的 Kotlin 文件(我将其命名为 我的),并介绍以下内容:KeyboardUtil.kt
fun View.hideKeyboard() {
val imm = ContextCompat.getSystemService(context, InputMethodManager::class.java) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
然后,您可以在任何视图上调用它以轻松关闭键盘。我使用 ViewBinding/DataBinding,它特别好用,例如:
fun submitForm() {
binding.root.hideKeyboard()
// continue now the keyboard is dismissed
}
对于那些寻找喷气背包的人,请回答。
val keyboardController = LocalSoftwareKeyboardController.current
//for showing the keyboard
keyboardController?.show()
//for hiding the keyboard
keyboardController?.hide()
Kotlin 版本:
fun showKeyboard(mEtSearch: EditText, context: Context) {
mEtSearch.requestFocus()
val imm: InputMethodManager =
context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(mEtSearch, 0)
}
您可以使用以下扩展来隐藏和显示软键盘:
fun Fragment.showKeyboard(view: View) {
view.isFocusableInTouchMode = true
view.requestFocus()
val imm = view.context?.getSystemService(Context.INPUT_METHOD_SERVICE)
as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT) }
fun Fragment.hideKeyboard(view: View) {
view.clearFocus()
val imm = view.context?.getSystemService(Context.INPUT_METHOD_SERVICE)
as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0) }
要调用扩展,只需在片段中按照以下内容操作即可:
showKeyboard(Your edittext ID)
hideKeboard(Your edittext ID)
我试过这个。效果良好,在 Nougat API 24 上进行了测试。
import android.app.Activity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
fun Activity.hideKeyboard() {
getInsetController().hide((WindowInsetsCompat.Type.ime()))
}
fun Activity.showKeyboard() {
getInsetController().show((WindowInsetsCompat.Type.ime()))
}
fun Fragment.hideKeyboard() {
requireActivity().getInsetController().hide((WindowInsetsCompat.Type.ime()))
}
fun Fragment.showKeyboard() {
requireActivity().getInsetController().show((WindowInsetsCompat.Type.ime()))
}
fun Activity.getInsetController() = WindowCompat.getInsetsController(window, window.decorView)
要以编程方式关闭或隐藏 Android 软键盘,您可以使用以下方法:
使用 InputMethodManager:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
使用 View 的 onEditorAction:
如果您有 EditText 视图,并且想要在用户按下“Done”或“Enter”键时隐藏软键盘,则可以使用 onEditorAction 侦听器:
yourEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0); return true; } return false; } });
以编程方式明确焦点:
另一种方法是以编程方式清除 EditText 视图中的焦点,这将导致软键盘被隐藏:
yourEditText.clearFocus();
请记住将 yourEditText 替换为对 EditText 视图的实际引用。此外,请确保您在 Android 清单文件中声明了相应的权限,特别是 android.permission.INPUT_METHOD。
这些方法将允许您以编程方式隐藏 Android 设备上的软键盘。
只需将 OnFocusChangeListener 添加到视图即可。例如,在本例中为 editText。
editText.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
if (!hasFocus) {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
val focusedView = currentFocus
if (imm != null && focusedView != null) {
imm.hideSoftInputFromWindow(focusedView.windowToken, 0)
}
}
}
评论