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

标签 android android-edittext keyboard

我想通过在 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);
}

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

What the first tap does.

现在我有两个问题:

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

  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) {...} 方法并在 onCreate() 中插入 onTouch 监听器方法:

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;
    }
});

关于android - 如何通过在编辑文本外轻按一下来隐藏键盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40452321/

相关文章:

android - 如何确定用户是否取消了 Google Play 订阅?

android - 如何在 ffmpeg 命令的时间戳日期中添加日期后缀 [st,nd,rd,th]?

java - 如何大写Android EditText中的每个字母?

java - 如何将光标移至自用户将数据放入后已以编程方式编辑的 EditText 的右边缘?

python - ctypes.windll.user32.GetKeyState 无法识别按键

android - 如何从 byte[] 创建一个 Drawable? (安卓)

java - WeatherLib -- Volley.jar 错误导致应用程序崩溃

android - 如何删除彩色 EditText 焦点边框

android - 覆盖默认的android键盘

linux - 读取键盘输入和鼠标输入