AndroidのViewを均等に配置
Viewの均等な配置は
LinearLayoutの
android:layout_weight=””
を使うことでできるようになる
均等に配置したいのなら
android:layout_weight=”1″
にすればいい
ただし、計算される領域は
もともとの幅や高さを元にいったん領域を確保して
余った領域を均等に分割しているので
これだけだとうまく機能しない
このため
均等に余白設定するには
配置方向に応じて
対象のViewの幅や高さを
0dpに指定する
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 | < LinearLayout android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "horizontal" /> < TextView android:layout_width = "0dp" android:layout_height = "@dimen/layout_common_size_xlarge" android:layout_margin = "@dimen/padding_small" android:layout_weight = "1" android:background = "@color/FlatLightGreen" android:gravity = "center" android:text = "view01" android:textColor = "@android:color/white" /> < TextView android:layout_width = "0dp" android:layout_height = "@dimen/layout_common_size_xlarge" android:layout_padding = "@dimen/padding_small" android:layout_weight = "1" android:gravity = "center" android:background = "@color/FlatLightGreen" android:text = "view02" android:textColor = "@android:color/white" /> < TextView android:layout_width = "0dp" android:layout_height = "@dimen/layout_common_size_xlarge" android:layout_padding = "@dimen/padding_small" android:layout_weight = "1" android:background = "@color/FlatLightGreen" android:gravity = "center" android:text = "view03" android:textColor = "@android:color/white" /> </ LinearLayout > |
Androidは、デバイスごとに画面の大きさや解像度が違う
このため、
android:layout_weight=””
を使うことで
簡単に均等配置が実現できる
もし、普通にやるなら
プログラムでディスプレイ解像度を計算して
Viewの幅や高さを設定する必要がある