SelectorInjection
SelectorInjection 是一个强大的 selector 注入器。它可以给 view 注入 selector 状态,免去了大量的 selecor 文件。
- 可以根据 shape 来着色产生 selector 状态
- 可根据普通情况下的颜色(normalColor)来自动生成按压态的颜色
- 支持 normal、pressed、checked、disabled 状态的效果
- 支持SVG和 TINT,并且二者可以配合使用
- 可以开启水波纹(ripple)按压效果
如果你的需求很简单,不妨试试「这篇文章」提到的一张图片实现 selector 的方案。
引入
1.添加 JitPack 仓库
repositories {
maven {
url "https://jitpack.io"
}
}
2.添加依赖
compile 'com.github.tianzhijiexian:SelectorInjection:1.1.6'
使用
我们可以根据需要将SelectorInjection
注入到任何一个 View 中去,产生一个新的自定义 View。
库中已经给出了 ImageButton、TextView、Button 等 view 的实现,已经提供的控件如下:
- SelectorTextView
- SelectorButton
- SelectorRadioButton
- SelectorImageButton (配合
app:inSrc=true
设置是否将 selector 效果作用于 src,不设置则作用于 background)
书写示例:
<kale.ui.view.SelectorTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:normalColor="#03a9f4"
app:normalDrawable="@drawable/btn_oval_shape"
app:normalStrokeColor="#ffffff"
app:normalStrokeWidth="4dp"
/>
效果
Type | Explain | Attribute |
---|---|---|
Color | app:normalColor="@color/green" app:normalDrawable="@drawable/shape_round_rectangle" |
|
Stroke | app:normalStrokeColor="#eeeeee" app:normalStrokeWidth="3dp" |
相应控件支持 normal、pressed、checked、disabled 四种状态,属性格式为:
- xxxDrawable
- xxxColor
- xxxStrokeColor
- xxxStrokeWidth
高级用法
自动计算按压颜色
提供的控件默认会在没有指定
app:pressedColor
的情况向下自动计算出按下后的颜色。如果你不希望开启这个功能,那么可以将app:smartColor
设置为 false。支持 shape
将 shape 对象作为 drawable 后,会自动将 normalColor 填充到 shape 的背景中并自动产生按下后的效果。
支持 layer-list
normalColor、pressedColor 等属性会作用于 layer-list 中标注有
@android:id/background
的 item 中。<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <!-- other item --> <item android:drawable="@drawable/btn_oval_shadow_mask"/> <!-- target item --> <item android:id="@android:id/background" > <shape android:shape="oval" > <solid android:color="@android:color/transparent" /> </shape> </item> </layer-list>
支持水波纹
在 Android5.0 以上支持了水波纹效果,可以通过
app:ripple = "true"
来开启:水波纹效果和其他属性不冲突,可以随意开关,但需要注意版本兼容问题。
支持 SVG
目前全版本兼容 SVG 图片(VectorDrawable),详细文档可以查看:SVG 和 Tint 应如何结合。
代码自动提示
支持 Android Studio 的代码提示,一般通过输入 normal、check、disable 等关键字就可以提示代码:
目标
Selector 的写法比较复杂,做业务开发的过程中我们在需求按压效果的时候必须要离开编写的 ui 界面转而定义 selector,打断了代码的编写流程。而增加的这些 selector 文件其实大多都是一次性使用,但数量众多,维护麻烦。
开发时借鉴了SelectorButton和MaterialDesignLibrary的写法,最终产生了能将颜色和形状两两组合的 selector 注入器。它支持且不仅仅支持下列的按钮,你还可以通过 layer-list 和 shape 的组合产生更多的按钮。
开发者
Jack Tony: developer_kale@foxmail.com
License
SelectorInjection is licensed under Apache License 2. View license.