Android Studio編 gravity と layout_gravity の違い
Android Studioでレイアウト作成時、画面の構成で layout_gravity と gravity の違いがわかってなかったのでメモしておこうと思います。
この属性は、LinearLayoutで表示する部品の位置付けをする属性なのですが毎回「gravityとlayout_gravity どっち使うんだっけ?」
と迷っていたので検証する事にしました。
まず各ボタンに layout_gravity と gravity の属性を付けて位置を確認。
わかりやすく gravity には赤。layout_gravityには青を塗りつけました。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="right" android:orientation="vertical" tools:context=".gravity"> <Button android:text="right" <span style="background-color: #ff0000;"> android:gravity="right"</span> android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ffff000a"/> <Button android:text="right" <span style="background-color: #0000ff;"> android:layout_gravity="right"</span> android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0a00ff"/> <Button android:text="center" <span style="background-color: #ff0000;"> android:gravity="center"</span> android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ffff000a"/> <Button android:text="center" <span style="background-color: #0000ff;">android:layout_gravity="center"</span> android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0a00ff"/> <Button android:text="left" <span style="background-color: #ff0000;">android:gravity="left"</span> android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ffff000a"/> <Button android:text="left" <span style="background-color: #0000ff;"> android:layout_gravity="left"</span> android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#ff0a00ff"/> </LinearLayout> |
赤の gravity ボタンの位置は変わらずテキストの表示位置が変わっていることがわかります。
一方、青のlayout_gravity は、ボタンの位置が変わってる事がわかります。
結果
gravityは部品の中(テキスト文字などの)位置指定。
layout_gravityは、レイアウトの中での位置指定。
されてる事がわかりました。
では、次にLinearLayout内に gravity の設定をします。
1 2 3 4 5 6 7 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" <span style="background-color: #ff0000;"> android:gravity="right"</span> android:orientation="vertical" tools:context=".gravity"> |
layout_gravity が属性についてる青ボタンはそのまま位置を保っています。
結果
LinearLayout の属性に gravity 属性で位置付けするとレイアウト内の部品は、layout_gravity で位置付けした部品以外は移動する。
という事がわかりました。
ちなみにLinearLayout の属性にLayout_gravity で位置付けしてもボタンの位置に変化はありませんでした。
layout_gravity は、あくまでレイアウト内での位置付けをするものだからレイアウト自体に設定しても意味がないという事でしょうか。
これですっきりしました(*´ェ`*)
次から迷わず書けそうです。