gpt4 book ai didi

android - 单击EditText外部后如何在android上隐藏软键盘?

转载 作者:IT老高 更新时间:2023-10-28 12:49:54 35 4
gpt4 key购买 nike

好的,大家都知道隐藏键盘需要实现:

InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

但是这里的大问题是当用户触摸或选择任何其他不是 EditText 或软键盘的地方时如何隐藏键盘?

我尝试在我的父 Activity 上使用 onTouchEvent() 但这仅在用户触摸任何其他 View 之外且没有 ScrollView 时才有效。

我尝试实现触摸、点击、聚焦监听器,但没有成功。

我什至尝试实现自己的 ScrollView 来拦截触摸事件,但我只能获取事件的坐标而不是点击的 View 。

有没有标准的方法来做到这一点?在 iPhone 中,这真的很容易。

最佳答案

以下代码段只是隐藏了键盘:

public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager =
(InputMethodManager) activity.getSystemService(
Activity.INPUT_METHOD_SERVICE);
if(inputMethodManager.isAcceptingText()){
inputMethodManager.hideSoftInputFromWindow(
activity.getCurrentFocus().getWindowToken(),
0
);
}
}

您可以将它放在实用程序类中,或者如果您在 Activity 中定义它,请避免使用 Activity 参数,或调用 hideSoftKeyboard(this) .

最棘手的部分是何时调用它。您可以编写一个迭代每个 View 的方法。在您的 Activity 中,并检查它是否是 instanceof EditText如果没有注册 setOnTouchListener到那个组件,一切都会到位。如果您想知道如何做到这一点,它实际上非常简单。这就是你要做的,你写一个像下面这样的递归方法,实际上你可以用它来做任何事情,比如设置自定义字体等......这是方法

public void setupUI(View view) {

// Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
hideSoftKeyboard(MyActivity.this);
return false;
}
});
}

//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}

就是这样,在你 setContentView 之后调用这个方法即可在你的 Activity 中。如果您想知道要传递什么参数,它是 id的父容器。分配 id到你的父容器像

<RelativeLayoutPanel android:id="@+id/parent"> ... </RelativeLayout>

并调用 setupUI(findViewById(R.id.parent)) ,仅此而已。

如果你想有效地使用它,你可以创建一个扩展的 Activity并将此方法放入,并使应用程序中的所有其他 Activity 扩展此 Activity 并调用其setupUI()onCreate()方法。

希望对你有帮助。

如果您使用超过 1 个 Activity ,请为父布局定义公共(public) id,例如 <RelativeLayout android:id="@+id/main_parent"> ... </RelativeLayout>

然后从 Activity 扩展一个类并定义 setupUI(findViewById(R.id.main_parent))在其OnResume()并扩展这个类而不是 ``Activity in your program


这是上述函数的 Kotlin 版本:

@file:JvmName("KeyboardUtils")

fun Activity.hideSoftKeyboard() {
currentFocus?.let {
val inputMethodManager = ContextCompat.getSystemService(this, InputMethodManager::class.java)!!
inputMethodManager.hideSoftInputFromWindow(it.windowToken, 0)
}
}

关于android - 单击EditText外部后如何在android上隐藏软键盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4165414/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com