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

Android 軟鍵盤透解:顯示原理、三種調整模式與狀態偵聽

編輯:關於 Android 程式設計

點擊輸入框會彈出軟鍵盤,鍵盤一來,可用高度就少了。系統如何處理這段被佔用的空間?我們能不能自己接管?本文把軟鍵盤的顯示機制和三種窗口調整模式講清楚,並給出偵聽鍵盤收放的可行方案。

一、軟鍵盤的本質

軟鍵盤其實就是一個 Dialog。InputMethodService 為輸入法創建了一個 Dialog,並設置好它的 Window 參數(如 Gravity),使其能夠顯示在屏幕底部或全屏。當我們點擊輸入框時,系統調整宿主 Activity 的主窗口,為輸入法騰出空間,然後把這個 Dialog 顯示出來。

二、windowSoftInputMode:控制主窗口的調整方式

Android 提供了一個名為 windowSoftInputMode 的屬性,讓開發者決定 Activity 主窗口如何響應鍵盤。可以在 AndroidManifest.xml 中這樣設置:

android:windowSoftInputMode="stateUnchanged|adjustPan"

這個屬性的取值分兩部分:豎線左側控制鍵盤自身的顯示狀態(如 stateUnspecified、stateVisible、stateHidden),右側控制主窗口的調整方式。本文聚焦於後者,共有三種取值。

模式一:adjustResize(壓縮模式)

設置為 adjustResize 時,Activity 主窗口總會被縮小,主動讓出鍵盤所需的空間。我們自定義一個 Layout 把各個測量與布局階段的日誌打出來觀察:

public class ResizeLayout extends LinearLayout {
    private static int count = 0;

    public ResizeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.e("onSizeChanged " + count++, "=>onResize called! w=" + w + ", h=" + h
                + ", oldw=" + oldw + ", oldh=" + oldh);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        Log.e("onLayout " + count++, "=>OnLayout called! l=" + l + ", t=" + t
                + ", r=" + r + ", b=" + b);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.e("onMeasure " + count++, "=>onMeasure called! widthMeasureSpec="
                + widthMeasureSpec + ", heightMeasureSpec=" + heightMeasureSpec);
    }
}

布局中把這個自定義 Layout 作為根節點,下方放一個靠底的 TextView:

<com.winuxxan.inputMethodTest.ResizeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/root_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" />

    <LinearLayout android:id="@+id/bottom_layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:gravity="bottom">
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/hello"
            android:background="#77777777" />
    </LinearLayout>
</com.winuxxan.inputMethodTest.ResizeLayout>

在清單文件中設置 android:windowSoftInputMode="adjustResize",運行後點擊文本框,日誌如下:

E/onMeasure 6: =>onMeasure called! widthMeasureSpec=1073742144, heightMeasureSpec=1073742024
E/onMeasure 7: =>onMeasure called! widthMeasureSpec=1073742144, heightMeasureSpec=1073742025
E/onSizeChanged 8: =>onSizeChanged called! w=320, h=201, oldw=320, oldh=377
E/onLayout 9: =>OnLayout called! l=0, t=0, r=320, b=201

可以看到根布局依次觸發了 onMeasure、onSizeChanged 和 onLayout,高度從 377 被壓到 201。運行結果上,原本貼底的 TextView 被頂到了鍵盤上方。

模式二:adjustPan(平移模式)

設置為 adjustPan 時,系統不去改變窗口大小,而是整體平移窗口內容,確保當前焦點控件不被鍵盤遮擋。把清單中的屬性改為 android:windowSoftInputMode="adjustPan" 後重新運行:

E/onMeasure 6: =>onMeasure called! widthMeasureSpec=1073742144, heightMeasureSpec=1073742200
E/onMeasure 7: =>onMeasure called! widthMeasureSpec=1073742144, heightMeasureSpec=1073742201
E/onLayout 8: =>OnLayout called! l=0, t=0, r=320, b=377

注意這裡 onSizeChanged 沒有被調用,說明窗口尺寸始終是 377 沒變,只是位置發生了偏移。運行結果上,底部的 TextView 也沒有被頂上去。

更具體地說:當輸入框不會被遮擋時,這個模式不做任何調整;一旦輸入框即將被遮擋,整個窗口(包括標題欄)才會向上平移,直到輸入框完全可見為止。

模式三:adjustUnspecified(自動模式)

這是不指定策略、交給系統自行決定的默認行為。系統會根據窗口內容中是否存在可滾動的布局視圖來判斷:如果存在這樣的視圖,就採用壓縮模式——因為內容本來就能滾動,縮小一點影響不大;否則採用平移模式。實踐中,如果希望鍵盤彈出時布局被壓縮,最保險的做法是顯式聲明 adjustResize,不要依賴系統推斷。

三、如何偵聽鍵盤的顯示與隱藏

Android 並沒有直接提供鍵盤狀態的監聽回調,但可以借用一個特性:鍵盤收放時,主窗口必然會重新布局。因此在壓縮模式下,我們跟蹤根布局的 onSizeChanged 就能感知鍵盤狀態變化(平移模式下該方法不會被觸發,這種方案也就失效了)。

自定義根布局,把尺寸變化通過接口拋出去:

public class ResizeLayout extends LinearLayout {
    private OnResizeListener mListener;

    public interface OnResizeListener {
        void OnResize(int w, int h, int oldw, int oldh);
    }

    public void setOnResizeListener(OnResizeListener l) {
        mListener = l;
    }

    public ResizeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (mListener != null) {
            mListener.OnResize(w, h, oldw, oldh);
        }
    }
}

Activity 中根據高度變化方向判斷鍵盤是彈出還是收起,並通過 Handler 切換某個 View 的顯示:

public class InputMethodTestActivity extends Activity {
    private static final int BIGGER = 1;
    private static final int SMALLER = 2;
    private static final int MSG_RESIZE = 1;

    class InputHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_RESIZE: {
                    if (msg.arg1 == BIGGER) {
                        findViewById(R.id.bottom_layout).setVisibility(View.VISIBLE);
                    } else {
                        findViewById(R.id.bottom_layout).setVisibility(View.GONE);
                    }
                }
                break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    }

    private InputHandler mHandler = new InputHandler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ResizeLayout layout = (ResizeLayout) findViewById(R.id.root_layout);
        layout.setOnResizeListener(new ResizeLayout.OnResizeListener() {
            public void OnResize(int w, int h, int oldw, int oldh) {
                int change = BIGGER;
                if (h < oldh) {
                    change = SMALLER;
                }
                Message msg = new Message();
                msg.what = MSG_RESIZE;
                msg.arg1 = change;
                mHandler.sendMessage(msg);
            }
        });
    }
}

這裡有一個必須注意的坑:不要直接在 OnResizeListener 裡修改 View 的顯示屬性。onSizeChanged 本身是在 layout 流程中被調用的,如果在其內部直接改動 visi ibility,就需要再次觸發 layout 才能生效,而我們此刻正處於 layout 過程中,這樣往往會導致測量與布局狀態錯亂甚至報錯。借助 Handler 把操作推到下一個消息循環,就能避開這個問題。

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