如何在点击EditText外部后隐藏Android上的软键盘?

2024-04-08

好吧,每个人都知道要隐藏键盘,您需要实现:

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

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

我尝试使用onTouchEvent()在我的父母身上Activity但这仅在用户触摸任何其他视图之外并且没有滚动视图时才有效。

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

我什至尝试实现自己的滚动视图来拦截触摸事件,但我只能获取事件的坐标,而不能获取单击的视图。

有没有标准的方法来做到这一点?在 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
        );
    }
}

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

最棘手的部分是何时调用它。您可以编写一个迭代每个View在您的活动中,并检查它是否是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在你的活动中。如果您想知道要传递什么参数,那就是id父容器的。分配一个id到你的父容器就像

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

并打电话setupUI(findViewById(R.id.parent)), 就这些。

如果您想有效地使用它,您可以创建一个扩展Activity并放入此方法,并使应用程序中的所有其他活动扩展此活动并调用其setupUI() in the onCreate() method.

如果您使用超过 1 个活动,请为父布局定义公共 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)
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在点击EditText外部后隐藏Android上的软键盘? 的相关文章

随机推荐