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

Android EditText 被軟鍵盤遮擋的處理方法

編輯:關於 Android 程式設計

在某些 Android 頁面中,特別是使用透明狀態列、全屏或特殊 UI 旗標時,EditText 可能會被軟鍵盤遮擋。即使設定 adjustResize,也可能因為系統 UI 配置而失效。這個問題可以透過監聽版面高度變化,手動調整底部 padding 來解決。

問題原因

正常情況下,系統 UI 會占據部分空間,例如狀態列、導覽列與鍵盤。若使用以下設定:

getWindow().getDecorView().setSystemUiVisibility(
    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
);

或:

getWindow().addFlags(
    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
);

可能會讓 App 內容延伸到系統 UI 下方,導致鍵盤彈起時,視窗不會自動縮放,底部輸入框就被遮住了。

解決思路

可以監聽 decorView 的版面變化,取得目前可見區域高度。當鍵盤彈起時,可見高度會減少,此時手動增加內容容器的 bottom padding,模擬 adjustResize 的效果。

KeyboardPatch 實作

public class KeyboardPatch {
    private Activity activity;
    private View decorView;
    private View contentView;

    public KeyboardPatch(Activity act, View contentView) {
        this.activity = act;
        this.decorView = act.getWindow().getDecorView();
        this.contentView = contentView;
    }

    public void enable() {
        activity.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
            | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
        );

        decorView.getViewTreeObserver()
            .addOnGlobalLayoutListener(onGlobalLayoutListener);
    }

    public void disable() {
        activity.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
            | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
        );

        decorView.getViewTreeObserver()
            .removeOnGlobalLayoutListener(onGlobalLayoutListener);
    }

    private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener =
        new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);

                int screenHeight = decorView.getContext()
                    .getResources()
                    .getDisplayMetrics()
                    .heightPixels;

                int diff = screenHeight - rect.bottom;

                if (diff != 0) {
                    if (contentView.getPaddingBottom() != diff) {
                        contentView.setPadding(0, 0, 0, diff);
                    }
                } else {
                    if (contentView.getPaddingBottom() != 0) {
                        contentView.setPadding(0, 0, 0, 0);
                    }
                }
            }
        };
}

使用方式

在 Activity 中建立 KeyboardPatch,並傳入需要調整的內容容器。

KeyboardPatch patch = new KeyboardPatch(
    this,
    findViewById(android.R.id.content)
);
patch.enable();

當鍵盤彈起時,內容容器會增加底部內距,讓 ScrollView 或輸入區域能自動捲動到可見位置。這種做法特別適合有透明狀態列、沉浸式模式或自訂全屏效果的頁面。

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