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

Android 軟鍵盤遮擋輸入框的四種解決方案

編輯:關於 Android 程式設計

當使用者點擊輸入框時,系統會彈出軟鍵盤。若頁面沒有做好配置,鍵盤可能會遮擋輸入框或底部按鈕。以下整理了四種常見解法。

問題效果如下:

方法一:使用 adjustPan

在 Activity 的 onCreate 中,於 setContentView 前設定:

getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
);

這種方式會讓視窗內容自動移動,嘗試保持焦點可見。

方法二:在 Manifest 中設定 windowSoftInputMode

在 AndroidManifest.xml 的 Activity 中加入:

android:windowSoftInputMode="stateVisible|adjustResize"

或使用:

android:windowSoftInputMode="adjustPan"

adjustResize 會讓視窗重新調整大小,adjustPan 則是平移內容。

方法三:使用 ScrollView 包裹內容

將最外層 Layout 替換成 ScrollView,或在外層再加一層 ScrollView,讓內容可以隨鍵盤捲動。

<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="輸入內容" />
    </LinearLayout>
</ScrollView>

方法四:自訂 Layout 監聽鍵盤狀態

若需要更精細控制,可以自訂 LinearLayout,在 onSizeChanged 中判斷高度變化,進而隱藏或顯示某些區塊。

public class KeyboardLayout extends LinearLayout {
    private static final int KEYBOARD_MIN_HEIGHT = 50;
    private KeyBordStateListener listener;

    public interface KeyBordStateListener {
        void stateChange(int state);
    }

    public void setKeyBordStateListener(KeyBordStateListener listener) {
        this.listener = listener;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        if (oldh - h > KEYBOARD_MIN_HEIGHT) {
            if (listener != null) {
                listener.stateChange(1);
            }
        } else {
            if (listener != null) {
                listener.stateChange(0);
            }
        }
    }
}

在 Activity 中,可以根據回呼結果隱藏或顯示 Logo、橫幅等非必要區域,讓輸入區獲得更多空間。

鍵盤彈出時:

鍵盤關閉時:

這四種方式各有適用場景。簡單頁面可以用 adjustResize 或 adjustPan;複雜頁面則可以搭配 ScrollView 或自訂 Layout 做更精細的控制。

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