Material Designではdividerについても言及している。作っておくと何かと便利なので作成しておく。
仕様
https://www.google.com/design/spec/components/dividers.html#dividers-specs
にある通り
- 厚さ1dp
- 12%白または黒の12%の不透明度(テーマの明暗により使い分け)
実践
- 色を作る
- スタイルを作る
- コンポーネント化する
- includeして使う
色を作る
まず色を作る。黒の12%は255 * 0.12 = 30.6 = 0x49 なので
values/colors.xml <color name="divider">#49000000</color>
スタイルを作る
次にスタイルである。縦と横に対応できるよう2つ作っておこう
values/style.xml <style name="divider"> <item name="android:background">@color/divider</item> </style> <style name="divider_horizontal" parent="divider"> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">1dp</item> </style> <style name="divider_vertical" parent="divider"> <item name="android:layout_width">1dp</item> <item name="android:layout_height">match_parent</item> </style>
ちなみにv11からはandroid:alphaが使えるのでそちらを利用するという手もある。
values-v11/style.xml <style name="divider"> <item name="android:background">@color/black</item> <item name="android:alpha">0.12</item> </style>
コンポーネント化
どのViewからも使えるようにコンポーネント化しておこう。階層が深くならないよう、mergeを用いる。
layout/component_divider.xml <?xml version="1.0" encoding="utf-8"?> <merge> <View style="@style/divider_horizontal" /> </merge>
Includeして使う
あとは任意のviewからincludeするだけ。
<?xml version="1.0" encoding="utf-8"?> <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="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical" tools:text="サンプルテキスト" /> <include layout="@layout/component_divider" /> </LinearLayout>
親Viewのpaddingの影響を受けてしまうのでその辺は工夫して使おう。