Android 实现点击输入框以外的区域隐藏软键盘

效果图如下:

在这里插入图片描述

代码实现如下:
首先创建一个工具类InputMethodUtil

public class InputMethodUtil {
    
    
    //隐藏软键盘
    public static boolean hideInputMethod(Activity activity, View view) {
    
    
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
    
    
            return imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
        return false;
    }
}

之后在InputMethodActivity类中实现点击输入框以外的区域,实现隐藏软件盘的效果

public class InputMethodActivity extends AppCompatActivity {
    
    
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input_method);
        editText = findViewById(R.id.editText);
        //请求焦点
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.RESULT_SHOWN);
    }

    //处理触摸事件的分发 是从dispatchTouchEvent开始的
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    
    
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
    
    
            //返回具有焦点的当前视图
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
    
    
                if (InputMethodUtil.hideInputMethod(this, v)) {
    
    
                    return true;
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isShouldHideInput(View v, MotionEvent ev) {
    
    
        if (v != null) {
    
    
            if (v instanceof EditText) {
    
    
                //命名一个元素为2个的整数数组
                int[] leftTop = {
    
    0, 0};
                //返回两个整数值,分别为X和Y,此X和Y表示此视图,在其屏幕中的坐标(以左上角为原点的坐标)
                v.getLocationInWindow(leftTop);
                int left = leftTop[0],
                        top = leftTop[1],
                        bottom = top + v.getHeight(),
                        right = left + v.getWidth();
                if (ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom) {
    
    
                    //如果点击的是输入框的区域,则返回false
                    return false;
                } else {
    
    
                    return true;
                }
            }
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/lu202032/article/details/122697142