需求场景:假设一个界面上有EditText,或者item中有EditText,使用EditText必然导致输入法软键盘显示隐藏,用户总是手动点击关闭关键盘体验稍微差一些。
因此:该工具类借鉴他人的一些方法,采用了一种比较便捷的方式:递归根布局,查看根布局的子View如果是非EditText,则设置Touch事件关闭软键盘,反之则继续递归。
先上效果图:
代码量非常少,核心代码就是一个递归算法:
/** * the function is recursive until the ViewGroup don't have childView * * @param view the root view in your layout */ public void setRootView(View view) { if (view != null) { if (!(view instanceof EditText)) { if (view != null) { view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { InputMethodUtils.getInstance(mActivity).hideSoftInput(); return false; } }); } } if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View inView = ((ViewGroup) view).getChildAt(i); setRootView(inView); } } }else{ throw new NullPointerException("root view is null"); } }
使用方式:
一:在build.gradle中添加依赖
Step 1. Add the JitPack repository to your build file; Add it in your root build.gradle at the end of repositories: allprojects { repositories { ... maven { url 'https://jitpack.io' } } } Step 2. Add the dependency dependencies { implementation 'com.github.KernHu:FilbertTool:v1.1' }
二:给xxx.xml 布局的根布局添加id
三:在onCreate中一行代码:
RecursInputMethod.getInstance(this).setRootView(findViewById(R.id.root_layout));
完整代码已上传GitHub
https://github.com/KernHu/FilbertTool
可以直接依赖,比较方便使用。