用 Xml 写 Shape Drawable 太繁琐了, so.
2019-04-10 本文已影响0人
大侠咕咚
so, DrawableBuilder is comming...
该 Builder 类主要提供语义化的 API 进行快捷的 Shape 创建操作。
通过语义化的 API 创建 shape drawable。
如下,几行代码就生成了一个线条背景 drawable。
Drawable drawable = new DrawableBuilder()
.line()
.build();
tvName.setBackground(drawable);
效果:
![](https://img.haomeiwen.com/i588640/e37e5fad2a89a47a.jpg)
而之前,我们大都是像如下方式来构造线条 shape。
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:width="1dp" android:color="#34495e"/>
</shape>
用 xml drawable 设置背景
tvName = (TextView) findViewById(R.id.tvName);
tvName.setBackgroundResource(R.drawable.bk_line_drawable);
样式
![](https://img.haomeiwen.com/i588640/c27430a57bc29705.jpg)
可以看到,两种方式效果一致,但是使用体验却更好。在写好布局文件后,都需要去 res 目录下再创建 drawable 文件,然后再切换回 Activity 或者布局文件进行背景设置,这就免不了我们跳来跳去的切换目录,很麻烦。
相比而言,语义化 API 就显得非常友好易用,如下所示:
Drawable drawable = new DrawableBuilder()
.line()
.build();
tvName.setBackground(drawable);
样式:
![](https://img.haomeiwen.com/i588640/57245e1e2e2efcea.jpg)
跟 xml 样式一致,并且代码更少,更易于使用。
以下是圆角等其他线条的展示。
指定度数的圆角线条
new DrawableBuilder()
.line()
.corner(4)
.build();
样式:
![](https://img.haomeiwen.com/i588640/bb680090396d9a7a.jpg)
椭圆形圆角
new DrawableBuilder()
.line()
.roundCorner()
.build();
样式:
![](https://img.haomeiwen.com/i588640/e75397680bdac6f9.jpg)
充满颜色的圆角
new DrawableBuilder()
.line()
.roundCorner()
.fill("#d35400")
.build();
样式:
![](https://img.haomeiwen.com/i588640/e088cacb47810a32.jpg)
虚线线条
new DrawableBuilder()
.line()
.dash()
.build();
样式
![](https://img.haomeiwen.com/i588640/4dba5e6236f7ab0d.jpg)
其他 API
除了以上语义化 API,还提供了相应自定义参数的 API,如下所示:
API | 说明 |
---|---|
lineWidth(int width) | 设置线条宽度,参数为具体数值,无需转换 |
lineColor(int lineColor) | 设置线条颜色 |
corner(float cornerRadius) | 设置圆角度数 |
dashWidth(float dashWidth) | 设置虚线每个单元长度 |
dashGap(float dashGap) | 设置虚线边框每个单元之间的间距 |
fill(@ColorInt int bkColor) | 设置填充颜色 |