【android・xml】RelativeLayoutを理解してボタンと画像を綺麗に合成する

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で定めたサイズの恩恵を
受けることができます。

画像+ボタンで組み合わせたいときに重宝できそう。

>株式会社シーポイントラボ

株式会社シーポイントラボ

TEL:053-543-9889
営業時間:9:00~18:00(月〜金)
住所:〒432-8003
   静岡県浜松市中央区和地山3-1-7
   浜松イノベーションキューブ 315
※ご来社の際はインターホンで「316」をお呼びください

CTR IMG