Android 監聽輸入法隱藏與顯示狀態切換

之前項目需求需要監聽在輸入法彈起和隱藏的時候,更改界面的相關顯示。一開始控制界面是否顯示是調用自己寫的工具類。
這裏寫圖片描述
也就是自己知道什麼時候會強制調用KeyBord的close和open方法,因此一切還很完美。
結果,坑爹的搜狗輸入法右上角竟然有一個隱藏輸入法的按鈕,我卻監聽不到這個按鈕事件。
一開始我的思路是盯着如何捕獲鍵盤按鈕事件,整的頭大。還是衆人拾柴火焰高,同事找到了其他方法,即監聽當前界面繪製佈局的改變。這裏我簡單包裝了一下。下面就是我自定義的輸入法狀態監聽類,

public abstract class onInputLayoutChangeListener implements ViewTreeObserver.OnGlobalLayoutListener {
    private static final UnifyLog lg = UnifyLogFactory.getLogger(onInputLayoutChangeListener.class.getSimpleName());

    private View rootView;
    private int curRectHeight = -1;

    public onInputLayoutChangeListener(View rootView) {
        this.rootView = rootView;
    }

    @Override
    public void onGlobalLayout() {
        Rect rect = new Rect();
        rootView.getWindowVisibleDisplayFrame(rect);
        int displayHight = rect.bottom - rect.top;
        int height = rootView.getHeight();
        lg.e("RectHeight:" + displayHight + ",DecorViewHeigt:" + height);
//        if (curRectHeight != displayHight) {
//            curRectHeight = displayHight;
//            onLayoutChange(displayHight, height);
//        }
        onLayoutChange(displayHight, height);
    }

    public abstract void onLayoutChange(int intputTop, int windowHeight);
}

調用方式:

 getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new onInputLayoutChangeListener(getWindow().getDecorView()) {
            @Override
            public void onLayoutChange(int intputTop, int windowHeight) {
                edtInputContent.setY(intputTop - edtInputContent.getMeasuredHeight());
            }
        });

intputTop==windowHeight則表示輸入法隱藏。
注:其實網上還有重寫ViewGroup容器的onMeasure方法,但我試了一下,那種方案侷限性太強,需要設置windowSoftInputMode爲特定值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章