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

设置间距的最佳方案——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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值