Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 監聽輸入法彈出與收起的可靠做法

編輯:關於 Android 程式設計

用過 iOS 的都會注意到一個細節:鍵盤收起的同時,輸入框也會自動關閉。那麼在 Android 上要怎麼監聽輸入法的彈出與收起?本文提供一種實測可靠的實作方式。

第一步:設定 windowSoftInputMode

先在 AndroidManifest 中為對應的 Activity 加上:

 android:windowSoftInputMode="adjustResize"

這樣每次輸入法彈出或收起時,系統都會重新計算版面高度,把佈局頂上去。

第二步:自訂一個能監聽尺寸變化的佈局

 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 old) { 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); } }

原理很單純:當輸入法彈出時,adjustResize 會讓根佈局的高度縮小,這個變化會觸發 onSizeChanged();反之則代表鍵盤收起。

第三步:在 Activity 中綁定監聽

把自訂佈局作為根佈局放進 XML,然後在 Activity 裡註冊回呼:

 mRootLayout.setOnResizeListener(this); @Override public void onResize(int w, int h, int oldw, int oldh) { //如果第一次初始化 if (oldh == 0) { return; } //如果用戶橫豎屏轉換 if (w != oldw) { return; } if (h < oldh) { //輸入法彈出 } else if (h > oldh) { //輸入法關閉 setCommentViewEnabled(false, false); } int distance = h - old; EventBus.getDefault().post(new InputMethodChangeEvent(distance,mCurrentImageId)); }

幾個實作細節值得注意

那段 if (oldh == 0) return; 是在過濾首次初始化的量測,此時尺寸資訊尚無意義,若不擋掉會誤判為「鍵盤已彈出」。而 if (w != oldw) return; 則是在排除螢幕旋轉——橫豎屏切換時寬高都會變,但與輸入法無關。

另外要提醒的是,這種「靠高度變化推斷鍵盤狀態」的做法有個前提:adjustResize 必須生效。如果 Activity 設定了 fullscreen 或 translucent 主題,或是 targetSdkVersion 在 AppCompat 下被設為 adjustNothing/adjustPan,高度就不會改變,監聽自然失效。遇到這種情況,可以改用在你的根佈局上量測「可見區域剩餘高度」的方式,效果相同但不受主題影響。

這樣一來,輸入法彈出與收起都能自動被捕捉,進而達到「收起鍵盤時一併關閉輸入框」的效果,體驗與 iOS 相當一致。

如果有更好的思路,歡迎留言討論。[Github demo 地址](https://github.com/gupengcheng/CheckSoftInputDemo)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved