1. 程式人生 > >android軟鍵盤擋住輸入框

android軟鍵盤擋住輸入框

最近遇到了軟鍵盤擋住輸入框的問題,上網蒐羅半天,找到了一篇針對這個問題講的比較全(好)的文章,地址放在下面:https://www.diycode.cc/topics/383

自己的收穫:

  1. 普通Activity(不帶WebView),直接在manifest檔案中對activity設定:android:windowSoftInputMode的值adjustPan或者adjustResize即可;
  2. 如果帶WebView:
    • 如果非全屏模式,可以使用adjustResize;
    • 如果是全屏模式,則使用AndroidBug5497Workaround進行處理。

注:

1、這裡的全屏模式即是頁面是全屏的,包括Application或activity使用了Fullscreen主題、使用了『狀態色著色』、『沉浸式狀態列』、『Immersive Mode』等等——總之,基本上只要是App自己接管了狀態列的控制,就會產生這種問題。

2、AndroidBug5497Workaround的使用:

  • AndroidBug5497Workaround類複製到專案中;
  • 在需要填坑的activity的setContentView()語句後,新增一句AndroidBug5497Workaround.assistActivity(this)即可。
class AndroidBug5497Workaround {

    // For more information, see https://issuetracker.google.com/issues/36911528
    // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.

    public static void assistActivity(Activity activity) {
        new AndroidBug5497Workaround(activity);
    }

    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams;

    private AndroidBug5497Workaround(Activity activity) {
        FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                possiblyResizeChildOfContent();
            }
        });
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
    }

    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            if (heightDifference > (usableHeightSansKeyboard / 4)) {
                // keyboard probably just became visible
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
            } else {
                // keyboard probably just became hidden
                frameLayoutParams.height = usableHeightSansKeyboard;
            }
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    }
}

總結:

遇到問題不可怕,多去網上找找,多想想,總能解決的!

走一段令人留戀的路,做一個不負自己的人。——共勉