既存の別のビューに応じて、RelativeLayout で XML のビューを水平または垂直に中央揃えにすることは可能ですか。
たとえば、次のようなものがあるとします。
2 番目のテキスト ビューは、最初のテキスト ビューの下に中央に表示されます。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="72dp"
android:text="dynamic text" />
<TextView
android:id="@+id/second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_marginLeft="43dp" <!-- Is there a rule to center it? -->
android:text="centered below text 1" />
</RelativeLayout>
XMLでそのようなものを実装することは可能ですか?まだ見逃しているルールはありますか?プログラムで位置を計算したくありません
ベストアンサー1
受け入れられているものよりはるかに優れた解決策があります。余分なネストはありません。小さいビューで 2 つの属性を組み合わせることでこれを実現できます。水平方向に中央揃えにする場合は、大きいビューに対して align_start と align_end の両方を使用できます。テキストの重力が "android:gravity="center" で中央揃えになっていることを確認してください。垂直方向の配置には、align_top と align_bottom の両方を使用します。以下は、レイアウトの変更された実装です。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="43dp" >
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/second"
android:layout_alignEnd="@+id/second"
android:gravity="center"
android:text="dynamic text" />
<TextView
android:id="@+id/second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:gravity="center"
android:text="centered below text 1" />
</RelativeLayout>
受け入れられた回答のように、不必要なネストは必要ありません。