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

Android 登入頁軟鍵盤遮擋登入按鈕的解決方案

編輯:關於 Android 程式設計

在登入頁面中,使用者需要輸入帳號與密碼。當軟鍵盤彈起時,常常會遮擋底部的登入按鈕,影響操作體驗。這個問題可以透過版面結構、視窗模式與滾動控制來解決。

版面結構設計

一個常見做法是將可滾動內容包在 ScrollView 中,把登入按鈕放在外層。這樣當鍵盤彈起時,可以透過調整滾動位置,讓輸入欄位保持可見。

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

    <LinearLayout
        android:id="@+id/ll_center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ScrollView
            android:id="@+id/sl_center"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:scrollbars="none">

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

                <EditText
                    android:id="@+id/sms_login_et_accout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="請輸入帳號" />

                <EditText
                    android:id="@+id/sms_login_et_password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="請輸入密碼"
                    android:inputType="textPassword" />
            </LinearLayout>
        </ScrollView>

        <Button
            android:id="@+id/sms_login_bt_confirm"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="登錄" />
    </LinearLayout>
</RelativeLayout>

設定 windowSoftInputMode

在 AndroidManifest.xml 中,可以為登入 Activity 設定:

android:windowSoftInputMode="stateHidden|adjustResize"

這會讓視窗在鍵盤彈起時調整大小,使 ScrollView 能重新配置可用空間。

讓 ScrollView 捲動到輸入區

當使用者點擊輸入框時,可以讓 ScrollView 捲到合適位置,避免焦點欄位被鍵盤遮住。

etAccount.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        changeScrollView();
        return false;
    }
});

private void changeScrollView() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            sl_center.scrollTo(0, sl_center.getHeight());
        }
    }, 300);
}

透過版面結構與滾動控制,即使鍵盤彈起,也能讓帳號、密碼與登入按鈕維持良好的可見性。這個思路也適用於註冊頁、表單頁與任何包含多個輸入欄位的畫面。

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