如何在使用 ScrollView 时隐藏软键盘输入

1 android scrollview android-softkeyboard

当我ScrollView在我的文件中使用 a 时,如何隐藏软键盘输入LinearLayout

我试图在我的活动类中实现以下内容,尽管这些解决方案都没有产生预期的结果:

(1)

@Override
public boolean onTouchEvent(MotionEvent event) 
{
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    return true;
}
Run Code Online (Sandbox Code Playgroud)

(2)

@Override
public boolean onTouchEvent(MotionEvent event) 
{
    ScrollView myScrollView = (ScrollView) findViewById(R.id.scrollview); //of course scrollview was id in layout then
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    return true;
}
Run Code Online (Sandbox Code Playgroud)

(3)

与#2 相同,但用LinearLayout代替ScrollView


这三种解决方案都不适合我。

我注意到的一件事是,当我ScrollViewlayout.xml文件中删除 时,一切都按预期工作。

小智 6

就我而言,我正在生成一个动态表单,它在滚动视图中包含太多编辑文本字段,并在滚动表单时隐藏键盘,我尝试了太多选项,但最终能够使用以下代码进行修复:

scrollView.setOnTouchListener(new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        if (event != null && event.getAction() == MotionEvent.ACTION_MOVE)
        {
            InputMethodManager imm = ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE));
            boolean isKeyboardUp = imm.isAcceptingText();

            if (isKeyboardUp)
            {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)