仅渐变作为背景
您可以通过以下方式实现此结果GradientDrawable
:
button.background = getRoundedTintedDrawable(Color.BLUE) // change it to any color
.
.
.
private fun getRoundedTintedDrawable(color: Int): Drawable {
GradientDrawable().run {
// set rounded corners
cornerRadius = DEFAULT_RADIUS // in dp
// set the gradient type
gradientType = GradientDrawable.LINEAR_GRADIENT // there is radial, oval, etc..
// set gradient orientation
orientation = GradientDrawable.Orientation.LEFT_RIGHT // right to left, top to bottom, etc...
// gradient colors
colors = intArrayOf(Color.BLACK, Color.BLUE) // change to any array of colors
return this
}
}
使用 getRoundedTintedDrawable 的点击事件效果
如果你想有任何点击事件效果,你需要使用 StateListDrawable
with View 状态和getRoundedTintedDrawable
上面的方法:
button.background = setColorSelection(Color.BLUE) // change it to any color
.
.
.
private fun setColorSelection(color: Int): StateListDrawable {
StateListDrawable().run {
setExitFadeDuration(PRESS_DURATION)
addState(ViewState.DISABLED.state, getRoundedTintedDrawable(getColorWithAlpha(color)))
addState(ViewState.PRESSED.state, getRoundedTintedDrawable(getDarkerColor(color)))
addState(ViewState.DEFAULT.state, getRoundedTintedDrawable(color))
return this
}
}
这是视图状态抽象枚举:
/**
* Possible view states list
* **/
internal enum class ViewState (val state: IntArray) {
PRESSED (intArrayOf(android.R.attr.state_pressed)),
FOCUSED (intArrayOf(android.R.attr.state_focused)),
DISABLED (intArrayOf(-android.R.attr.state_enabled)),
CHECKED (intArrayOf(android.R.attr.state_checked)),
DEFAULT (intArrayOf())
}
这是和颜色计算器,以获得更暗和更半透明的颜色:
/**
* @return a [Color] darker than [color]
* **/
private fun getDarkerColor(color: Int): Int{
val hsv = FloatArray(3)
Color.colorToHSV(color, hsv)
hsv[2] *= BRIGHTNESS_REDUCTION // change the brightness of the color
return Color.HSVToColor(hsv)
}
// @return a [Color] more translucent than [color]
private fun getColorWithAlpha(color: Int, ratio: Float = ALPHA_FADE_DISABLE): Int {
return Color.argb((Color.alpha(color) * ratio).roundToInt(), Color.red(color), Color.green(color), Color.blue(color))
}
我们可以设置一些默认值来帮助我们改变效果与按钮的交互方式。
private companion object {
const val BRIGHTNESS_REDUCTION = 0.8f
const val PRESS_DURATION = 200 //ms
const val ALPHA_FADE_DISABLE = 0.4f
const val DEFAULT_COLOR = Color.GRAY
const val DEFAULT_RADIUS = 10f // dp
}
希望有帮助:)