Android layout實現輸入法彈出後,佈局整體上移
阿新 • • 發佈:2019-02-18
今天在給手機設定PIN碼時,發現在設定PIN碼的頁面,輸入框和底部的按鈕會隨著輸入法的彈出而上移,從而不至於被輸入法擋住。
這樣的佈局是怎麼實現的呢?經過嘗試,我也實現了同樣的效果。下面來進行分析。
先分別看下輸入法未彈出和彈出後的效果:
下面看具體實現:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height ="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20sp"
android:paddingTop="30dp"
android:text="請輸入密碼:"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:gravity="center_vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height ="wrap_content">
<EditText
android:id="@+id/gridview"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:hint="edit here"
android:inputType="textPassword"
android:gravity="center"/>
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:dividerPadding="10dp">
<Button
android:id="@+id/smit_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="取 消" />
<Button
android:id="@+id/cancel_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="確 定" />"
</LinearLayout>
</LinearLayout>
整個佈局由三部分組成:
頂部是一個TextView,文字為“請輸入密碼”,底部是一個Linearlayout,包含兩個Button。這兩部分的高度是固定的。
其餘部分是一個Linearlayout,高度為0dp並且其layout_weight為1,這個屬性是一個關鍵,表示這個Linearlayout將會填充除了其餘兩部分之外的所有螢幕空間。在這個Linearlayout裡,輸入框被一個ScrollView包含,這個ScrollView是另一個關鍵,如果不用ScrollView的話,中間部分就不會上移,輸入法彈出後就會遮擋底部按鈕。
注意
經過測試,下面幾種情況下,這樣佈局上移的效果會失效:
1.在Manifest裡給activity加上android:windowSoftInputMode=”adjustPan”這樣的屬性。
2.實現了沉浸式狀態列,比如在setContentView之前加上這些:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
那如果要實現沉浸式狀態列又要保持佈局不會被輸入法遮擋,怎麼辦呢?
只要在根佈局加上android:fitsSystemWindows=”true”即可,效果如下(為方便看效果我把背景改成了黃色):