设置间距的最佳方案——LinearLayout 的divider
实际上 LinearLayout
已经有一个处理这种元素之间的间距的属性了。这个属性却没怎么被大家发现,一直很低调,但它的效果相当神奇。所以我们说的第三个方案就是使用一个固定高宽的 Drawable
作为 LinearLayout
的 元素分隔线(divider):
1
2
3
4
5
6
7
8
9
10
11
|
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
shape
xmlns:android
=
"http://schemas.android.com/apk/res/android"
android:shape
=
"rectangle"
>
<
size
android:width
=
"@dimen/spacing_medium"
android:height
=
"@dimen/spacing_medium"
/>
<
solid
android:color
=
"<a href="
http://www.jobbole.com/members/android/"
rel
=
"nofollow"
>@android</
a
>:color/transparent" />
</
shape
>
|
现在你就可以把这个新创建的 Drawable 设为LinearLayout 的 divider,这样这个Drawable 就能让元素之间产生间距了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<
LinearLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
android:layout_width
=
"match_parent"
android:layout_height
=
"wrap_content"
android:divider
=
"@drawable/spacer_medium"
android:orientation
=
"vertical"
android:padding
=
"@dimen/spacing_medium"
android:showDividers
=
"middle"
>
<!-- TextView -->
<
LinearLayout
android:id
=
"@+id/buttons_container"
android:layout_width
=
"match_parent"
android:layout_height
=
"wrap_content"
android:divider = "@drawable/spacer_medium"
android:orientation
=
"horizontal"
android:showDividers = "middle"
>
<!-- Buttons -->
</
LinearLayout
>
</
LinearLayout
>
|
总结
Android 框架里面有许多的特性可以用来实现一些不常见的方案,而且最后效果出其不意。定义 Drawable
就是其中一种途径。如果你能吃透Android 里面的 Drawable
,那么你的代码也可能大大地精简。
注意:文章LinearLayout的divider 属性设置是Android API 11 之后加进去的,这意味着Android API 11之前的设备要使用这个divider需要LinearLayoutCompat。