每个人都知道要隐藏一个键盘,你需要实现:

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

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

我尝试在我的父活动上使用onTouchEvent(),但只有当用户在任何其他视图之外触摸并且没有滚动视图时才有效。

我试图实现一个触摸,点击,焦点监听器,但没有任何成功。

我甚至尝试实现我自己的滚动视图来拦截触摸事件,但我只能得到事件的坐标,而不是视图被单击。

有标准的方法来做这件事吗?在iPhone中,这非常简单。


当前回答

你可以试试下面的方法,它对我很有用:)

这种方式可以应用于活动或片段,它也与ScrollView兼容。

我们将ScrollView作为顶级布局,在LinearLayout中声明id parentView,并添加如下两个属性:

android:id="@+id/parentView"
android:clickable="true"
android:focusableInTouchMode="true"

在代码中,编写如下函数:

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

然后为根视图注册一个OnFocusChangeListener(写入onCreate方法),使Activity中的所有EditText受到影响:

parentLayout.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    hideSoftKeyboard(your_activity_name.this);
                }
            }
        });

其他回答

我稍微修改了一下@ navneth -g的答案,增加了null活动焦点处理,避免了创建OnTouchListener的多个实例,键盘隐藏时删除焦点,屏幕滚动时删除隐藏键盘,在小设备上方便。

//In general, the view parameter is root layout
fun Activity.hideKeyboardOnClickOutsideEditText(view: View) {
    // Set up touch listener for non-text box views to hide keyboard.
    var previousAction = 0
    val onTouchListener = View.OnTouchListener { v, event ->
        if (currentFocus != null
            && event.action != MotionEvent.ACTION_DOWN
            && event.action != MotionEvent.ACTION_MOVE
            && previousAction != MotionEvent.ACTION_MOVE
        ) {
            currentFocus?.clearFocus()
            v?.hideKeyboard()
        }
        previousAction = event.action
        false
    }

    if (view !is EditText) {
        view.setOnTouchListener(onTouchListener)
    }

    //If a layout container, iterate over children and seed recursion.
    if (view is ViewGroup) {
        for (i in 0 until view.childCount) {
            val innerView = view.getChildAt(i)
            hideKeyboardOnClickOutsideEditText(innerView)
        }
    }
}
   
//in root layout.xml
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"

你可以通过以下步骤来实现这一点:

Make the parent view(content view of your activity) clickable and focusable by adding the following attributes android:clickable="true" android:focusableInTouchMode="true" Implement a hideKeyboard() method public void hideKeyboard(View view) { InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } Lastly, set the onFocusChangeListener of your edittext. edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { hideKeyboard(v); } } });

正如下面的一条评论所指出的,如果父视图是ScrollView,这可能不起作用。对于这种情况,clickable和focusableInTouchMode可以直接添加到ScrollView下面的视图上。

它太简单了,只是让你最近的布局点击一个可聚焦的代码:

android:id="@+id/loginParentLayout"
android:clickable="true"
android:focusableInTouchMode="true"

然后为那个布局写一个方法和一个OnClickListner,所以当最上面的布局被触及的时候,它会调用一个方法,在这个方法中你会写代码来解除键盘。以下是两者的代码; //你必须在OnCreate()中写这个

 yourLayout.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View view) {
                    hideKeyboard(view);
                }
            });

从侦听器调用的方法:-

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

好吧,我设法某种程度上解决了这个问题,我在我的活动上覆盖了dispatchTouchEvent,在那里我使用下面的隐藏键盘。

 /**
 * Called to process touch screen events. 
 */
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {

    switch (ev.getAction()){
        case MotionEvent.ACTION_DOWN:
            touchDownTime = SystemClock.elapsedRealtime();
            break;

        case MotionEvent.ACTION_UP:
            //to avoid drag events
            if (SystemClock.elapsedRealtime() - touchDownTime <= 150){  

                EditText[] textFields = this.getFields();
                if(textFields != null && textFields.length > 0){

                    boolean clickIsOutsideEditTexts = true;

                    for(EditText field : textFields){
                        if(isPointInsideView(ev.getRawX(), ev.getRawY(), field)){
                            clickIsOutsideEditTexts = false;
                            break;
                        }
                    }

                    if(clickIsOutsideEditTexts){
                        this.hideSoftKeyboard();
                    }               
                } else {
                    this.hideSoftKeyboard();
                }
            }
            break;
    }

    return super.dispatchTouchEvent(ev);
}

编辑:getFields()方法只是一个在视图中返回带有文本字段的数组的方法。为了避免每次触摸都创建这个数组,我创建了一个名为sFields的静态数组,它在getFields()方法中返回。该数组在onStart()方法上初始化,例如:

《新经》[英文]


它不是完美的,拖动事件时间只是基于启发式,所以有时它不会隐藏在执行长clics时,我也完成了创建一个方法来获得每个视图的所有editTexts;否则,当单击其他EditText时,键盘将隐藏和显示。

不过,更干净、更短的解决方案还是受欢迎的

你可以使用这段代码,使用你的主布局Id而不是"mainRelativeLayout"

//hide Soft keyboard on click outside  the input text
    findViewById(R.id.mainRelativeLayout).setOnClickListener(new 
View.OnClickListener() {
        @Override
        public void onClick(View v) {
            InputMethodManager im = (InputMethodManager) 
getSystemService(INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 
0);
        }

    });