画面中央にレイアウトを配置したい。
10 に答える
ステップ #1: 画面の中央に配置したいものをフルスクリーンでラップしますRelativeLayout
。
ステップ #2: その子ビュー ( の中央に配置するビューRelativeLayout
) にandroid:layout_centerInParent="true"
属性を指定します。
XML 属性 android:layout_gravity" を使用して、レイアウトを含む任意のビューにセンタリングを適用できます。おそらく、値 "center" を指定することをお勧めします。
このオプションの可能な値のリファレンスは、http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html#attr_android: layout_gravityで見つけることができます。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
<ProgressBar
android:id="@+id/ProgressBar01"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="wrap_content"></ProgressBar>
<TextView
android:layout_below="@id/ProgressBar01"
android:text="@string/please_wait_authenticating"
android:id="@+id/txtText"
android:paddingTop="30px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
</RelativeLayout>
を使用してビューを中央に配置できました
android:layout_centerHorizontal="true"
と
android:layout_centerVertical="true"
パラメータ。
1つのビューを中央に配置する場合は、これを使用します。この場合、layout_heightはmatch_parentであるため、TextViewはXMLの最下部のビューである必要があります。
<TextView
android:id="@+id/tv_to_be_centered"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:gravity="center"
android:text="Some text"
/>
更新された回答: Constraint Layout
現在の Android のトレンドは、Constraint レイアウトを使用することです。を使用してビューを中央に配置するのは簡単ですがRelativeLayout
(他の回答が示しているように)、はより複雑なレイアウトConstraintLayout
の場合よりも強力です。RelativeLayout
したがって、今どのように行うかを学ぶ価値があります。
ビューを中央に配置するには、ハンドルを親の 4 つの側面すべてにドラッグします。
そのコードでは、両方のプロパティが必要な場合があります
android:layout_gravity="center"
android:layout_centerHorizontal="true"
RelativeLayoutの中央揃えにしたい要素に android:layout_centerInParent="true" を追加
ConstraintLayout を使用します。親画面の幅と高さに応じてビューを中央に配置する例を次に示します。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#FF00FF"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHeight_percent=".6"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent=".4"></LinearLayout>
</android.support.constraint.ConstraintLayout>
ConstraintLayout の最新バージョンを取得するには、gradle を変更する必要がある場合があります。
dependencies {
...
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}