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

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

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

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

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

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

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


当前回答

我在活动中实现了dispatchTouchEvent来做到这一点:

private EditText mEditText;
private Rect mRect = new Rect();
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    final int action = MotionEventCompat.getActionMasked(ev);

    int[] location = new int[2];
    mEditText.getLocationOnScreen(location);
    mRect.left = location[0];
    mRect.top = location[1];
    mRect.right = location[0] + mEditText.getWidth();
    mRect.bottom = location[1] + mEditText.getHeight();

    int x = (int) ev.getX();
    int y = (int) ev.getY();

    if (action == MotionEvent.ACTION_DOWN && !mRect.contains(x, y)) {
        InputMethodManager input = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        input.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }
    return super.dispatchTouchEvent(ev);
}

我测试过了,效果完美!

其他回答

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

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下面的视图上。

我喜欢调用dispatchTouchEvent的方法由htafoya,但是:

我不理解定时器的部分(不知道为什么测量停机时间应该是必要的?) 我不喜欢注册/取消注册所有的EditTexts与每一个视图的变化(可能是相当多的视图变化和编辑文本在复杂的层次结构)

所以,我做了一个更简单的解决方案:

@Override
public boolean dispatchTouchEvent(final MotionEvent ev) {
    // all touch events close the keyboard before they are processed except EditText instances.
    // if focus is an EditText we need to check, if the touchevent was inside the focus editTexts
    final View currentFocus = getCurrentFocus();
    if (!(currentFocus instanceof EditText) || !isTouchInsideView(ev, currentFocus)) {
        ((InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE))
            .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
    return super.dispatchTouchEvent(ev);
}

/**
 * determine if the given motionevent is inside the given view.
 * 
 * @param ev
 *            the given view
 * @param currentFocus
 *            the motion event.
 * @return if the given motionevent is inside the given view
 */
private boolean isTouchInsideView(final MotionEvent ev, final View currentFocus) {
    final int[] loc = new int[2];
    currentFocus.getLocationOnScreen(loc);
    return ev.getRawX() > loc[0] && ev.getRawY() > loc[1] && ev.getRawX() < (loc[0] + currentFocus.getWidth())
        && ev.getRawY() < (loc[1] + currentFocus.getHeight());
}

但有一个缺点:

从一个EditText切换到另一个EditText使键盘隐藏并重新显示——在我的例子中,这是理想的方式,因为它显示您在两个输入组件之间切换。

唯一有效的代码

private var viewHeight = 0

private fun setRootViewListener() {
    binding.root.apply {
        viewTreeObserver.addOnGlobalLayoutListener {
            viewHeight = height
        }
    }
}

override fun dispatchTouchEvent(event: MotionEvent): Boolean {
    currentFocus?.let {
        if (it is EditText && event.y < viewHeight - it.measuredHeight) {
            hideKeyboard(it)
        }
    }
    return super.dispatchTouchEvent(event)
}

我的解决方案隐藏键盘在外面点击任何活动,与所有编辑文本。没有一一说明。

首先添加到布局xml的根视图: android:点击= " true " android: focusableInTouchMode = " true "

接下来,创建一个你想隐藏键盘的所有活动的父活动,并指定onResume()方法:

 @Override
    protected void onResume() {
        super.onResume();
        //getting Root View that gets focus
        View rootView =((ViewGroup)findViewById(android.R.id.content)).
                getChildAt(0);
        rootView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    hideKeyboard(AbstractActivity.this);
                }
            }
        });
    }

用这个General activity(继承能力!)扩展你的活动,就是这样,每次任何EditText(在任何扩展的活动上)将失去焦点,键盘将被隐藏。

附注:hideKeyboard方法:

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

context.getCurrentFocus()不需要指定特定的EditText视图..

要解决这个问题,你必须首先使用Edittext的setOnFocusChangeListener

edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    Log.d("focus", "focus loosed");
                    // Do whatever you want here
                } else {
                    Log.d("focus", "focused");
                }
            }
        });

然后你需要做的是覆盖dispatchTouchEvent在活动中包含的编辑文本见下面的代码

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if ( v instanceof EditText) {
            Rect outRect = new Rect();
            v.getGlobalVisibleRect(outRect);
            if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
                Log.d("focus", "touchevent");
                v.clearFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }
    return super.dispatchTouchEvent(event);
}

现在会发生的是当用户点击外部时首先dispatchTouchEvent会被调用它会从编辑文本中清除焦点现在你的OnFocusChangeListener会被调用焦点已经改变了现在在这里你可以做任何你想做的希望它能起作用