abstract:用過ios的都知道ios上輸入法關(guān)閉的同時(shí)會(huì)自動(dòng)關(guān)閉輸入框,那么在android上如何實(shí)現(xiàn)監(jiān)聽輸入法彈出和關(guān)閉呢?本篇文章就為你提供了一種可靠的實(shí)現(xiàn)方式。首先在AndroidManifest中配置android:windowSoftInputMode="adjustResize"這樣每次輸入法彈出和關(guān)閉都會(huì)重新計(jì)算高度實(shí)現(xiàn)把布局頂上去的效果然后我們要自定義一個(gè)布局,監(jiān)聽布局大小
用過ios的都知道ios上輸入法關(guān)閉的同時(shí)會(huì)自動(dòng)關(guān)閉輸入框,那么在android上如何實(shí)現(xiàn)監(jiān)聽輸入法彈出和關(guān)閉呢?本篇文章就為你提供了一種可靠的實(shí)現(xiàn)方式。
首先在AndroidManifest中配置
android:windowSoftInputMode="adjustResize"
這樣每次輸入法彈出和關(guān)閉都會(huì)重新計(jì)算高度實(shí)現(xiàn)把布局頂上去的效果
然后我們要自定義一個(gè)布局,監(jiān)聽布局大小變化
public class CheckSoftInputLayout extends FrameLayout { private OnResizeListener mOnResizeListener; public CheckSoftInputLayout(Context context) { super(context); } public CheckSoftInputLayout(Context context, AttributeSet attrs) { super(context, attires); } public CheckSoftInputLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(21) public CheckSoftInputLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, old); if (mOnResizeListener != null) { mOnResizeListener.onResize(w, h, oldw, old); } } public void setOnResizeListener(OnResizeListener listener) { this.mOnResizeListener = listener; } public interface OnResizeListener { void onResize(int w, int h, int oldw, int old); } }
然后把上面的自定義布局作為跟布局放到你需要的Activity中去,然后在Activity中綁定監(jiān)聽事件
mRootLayout.setOnResizeListener(this);
mRootLayout.setOnResizeListener(this);
@Overridepublic void onResize(int w, int h, int oldw, int oldh) { //如果第一次初始化 if (oldh == 0) { return; } //如果用戶橫豎屏轉(zhuǎn)換 if (w != oldw) { return; } if (h < oldh) { //輸入法彈出 } else if (h > oldh) { //輸入法關(guān)閉 setCommentViewEnabled(false, false); } int distance = h - old; EventBus.getDefault().post(new InputMethodChangeEvent(distance,mCurrentImageId)); }
這樣只要輸入法彈出和關(guān)閉就能自動(dòng)實(shí)現(xiàn)監(jiān)聽,達(dá)到關(guān)閉輸入框的效果,這樣就和蘋果的體驗(yàn)很一致。