EditText一行程式碼自動隱藏輸入法軟鍵盤(Soft input)
阿新 • • 發佈:2019-01-29
需求場景:假設一個介面上有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));
https://github.com/KernHu/FilbertTool
可以直接依賴,比較方便使用。