如何仅在edittext之外一键隐藏键盘? [英] How to hide keyboard just by one tap outside of an edittext?

查看:89
本文介绍了如何仅在edittext之外一键隐藏键盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to hide the keyboard by tapping outside of edittext. This is my xml code:

<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):

This is my java code (MainActivity):

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

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

But I have to tap twice to hide keyboard. The first tap just changes "next" (for last edittext it's "done") to "enter" icon, then the second tap hides the keyboard. This is what that happen by the first tap:

现在我有两个问题:

  1. 如何解决该问题并一键隐藏键盘?

  1. How can I fix it and hide keyboard by just one tap?

是否可以对我的所有edittext(全部使用一个代码)执行此操作?

Is it possible to do it for all of my edittext (one code for all)?

推荐答案

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

Try to replace onClick with onTouch. For this you need to change your layout attributes like this:

<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侦听器方法:

Then remove rl_main_onClick(View view) {...} method and insert onTouch listener method inside of 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;
    }
});

这篇关于如何仅在edittext之外一键隐藏键盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆