如何通过在编辑文本外轻按一下来隐藏键盘?

新手上路,请多包涵

我想通过在 edittext 之外点击来隐藏键盘。这是我的 xml 代码:

 <RelativeLayout
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:onClick="rl_main_onClick">
<RelativeLayout
  //Here there are some widgets including some edittext.
</RelativeLayout>

这是我的 Java 代码(MainActivity):

 public void rl_main_onClick(View view) {
    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}

但我必须点击两次才能隐藏键盘。第一次点击只是将“下一步”(对于最后一个编辑文本是“完成”)更改为“输入”图标,然后第二次点击隐藏键盘。这是第一次点击时发生的情况:

第一次点击做什么。

现在我有两个问题:

  1. 如何修复它并一键隐藏键盘?

  2. 是否可以对我所有的编辑文本(一个代码)执行此操作?

原文由 Reyhaneh Sharifzadeh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 270
2 个回答

尝试将 onClick 替换为 onTouch 。为此,您需要像这样更改布局属性:

 <RelativeLayout
    android:id="@+id/relativeLayout"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <RelativeLayout>

        // widgets here

    </RelativeLayout>

</RelativeLayout>

然后删除 rl_main_onClick(View view) {...} 方法并插入 onTouch 监听器方法 onCreate()

 findViewById(R.id.relativeLayout).setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        return true;
    }
});

原文由 Marat 发布,翻译遵循 CC BY-SA 3.0 许可协议

我使用下面的过程。它非常适合我。在您的活动类中添加以下功能。

   override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
    val v = currentFocus
    if (v is EditText) {
        val outRect = Rect()
        v.getGlobalVisibleRect(outRect)
        if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
            Log.d("focus", "touchevent")
            v.clearFocus()
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(v.windowToken, 0)
        }
    }
}
return super.dispatchTouchEvent(event)}

您可以使用以下代码检查焦点状态。活动和片段

appCompatEditText.onFocusChangeListener = View.OnFocusChangeListener { view, hasFocus ->
            if (!hasFocus) {
                toast("Focus Off")
            }else {
                toast("Focus On")
            }
        }

原文由 Shohel Rana 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题