【发布时间】:2021-04-21 13:58:19
【问题描述】:
我想以编程方式更改现有的可绘制状态列表(默认和按下)颜色。
这是我要编辑的自定义可绘制对象:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<ripple android:color="#1AFFFFFF">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
<corners android:radius="5dp" />
</shape>
</item>
</ripple>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/colorPrimary" />
<corners android:radius="5dp" />
</shape>
</item>
</selector>
我已尝试How can I change colors in my StateListDrawable?,但出现错误:
val customButtonTest: Drawable
get() {
val stateListDrawable = ContextCompat.getDrawable(context, R.drawable.custom_button) as StateListDrawable
val drawableContainerState = stateListDrawable.constantState as DrawableContainer.DrawableContainerState
val children = drawableContainerState.children
val selectedItem = children[0] as GradientDrawable
selectedItem.setColor(Color.parseColor("#FD00DF"))
return stateListDrawable.current
}
**ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.GradientDrawable**
由于我打算将它用于 BandingAdapter,我如何更改两种状态颜色并将其作为可绘制对象返回?
谢谢
** 已编辑 ---
val customButtonTest: Drawable
get() {
val stateListDrawable =
ContextCompat.getDrawable(context, R.drawable.custom_button) as StateListDrawable
val drawableContainerState =
stateListDrawable.constantState as DrawableContainer.DrawableContainerState
val children = drawableContainerState.children
val pressedState = children[0] as RippleDrawable
val defaultState = children[1] as GradientDrawable
pressedState.setColor(ColorStateList.valueOf(Color.parseColor("#1AFFFFFF")))
defaultState.setColor(Color.parseColor("#4267b2"))
drawableContainerState.addChild(pressedState)
drawableContainerState.addChild(defaultState)
return drawableContainerState.newDrawable()
}
如何更改波纹容器内的项目纯色?作为
pressedState.setColor(ColorStateList.valueOf(Color.parseColor("#1AFFFFFF")
改变波纹颜色本身。
【问题讨论】:
-
试试这个:
val selectedItem = children[0] as RippleDrawable而不是GradientDrawable -
很好看。谢谢
标签: android mobile data-binding customization drawable