2023-11-06
RelativeLayoutは、width・height共にwrap_contentだった場合、一番最初に
定義したオブジェクトによって大きさをかえることができます。
<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/confirm" android:layout_width="190dp" android:layout_height="50dp" android:layout_marginTop="20dp" android:layout_centerHorizontal="true" android:text="ボタン" android:textColor="#fff" android:gravity="center" /> <ImageView android:id="@+id/character" android:layout_width="35dp" android:layout_height="35dp" android:layout_marginStart="12dp" android:layout_marginTop="25dp" android:translationZ="2dp" android:src="@drawable/chara" tools:ignore="MissingConstraints" /> </RelativeLayout>
こちらがデザイン
例えば、スクショのButtonではwidth=190dp・height=50dpと設定していますが、
実際のRelativeLayoutの範囲はボタンと全く同じ大きさになっています。
実際はmarginTop=”20dp”をしているので、ボタンの位置はトップから離れていますが
何も設定しない状態では、RelativeLayotとButtonは密接している状態となっています。
下に定義してあるimageViewもButtonの範囲までしかRelativLayoutが
延びないので、他のandroid機種に変更したり横向きに表示したりしても
画面の影響を受けず均等に表示させることができます。
なお、この下にオブジェクト作り続けてもButtonで定めたサイズの恩恵を
受けることができます。
画像+ボタンで組み合わせたいときに重宝できそう。