巧用Drawable 实现Android UI 元素间距效果

来源:互联网 发布:vs2017如何编写c语言 编辑:程序博客网 时间:2024/06/06 01:13

设置间距的最佳方案——LinearLayout 的divider

实际上 LinearLayout 已经有一个处理这种元素之间的间距的属性了。这个属性却没怎么被大家发现,一直很低调,但它的效果相当神奇。所以我们说的第三个方案就是使用一个固定高宽的 Drawable 作为 LinearLayout 的 元素分隔线(divider):

1
2
3
4
5
6
7
8
9
10
11
<?xmlversion="1.0"encoding="utf-8"?>
<shapexmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
 
    <size
        android:width="@dimen/spacing_medium"
        android:height="@dimen/spacing_medium"/>
 
    <solidandroid: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
<LinearLayoutxmlns: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。

0 0
原创粉丝点击