我如何更改可绘制的涟漪的纯色


<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="?android:attr/colorControlHighlight">
    <item>
        <selector>
            <item android:state_selected="true">
                <layer-list>
                    <item android:left="-5dp"
                          android:top="-5dp"
                          android:right="-5dp">
                        <shape android:shape="rectangle">
                            <stroke android:width="3dp"
                                    android:color="@android:color/white"/>
                            <solid android:color="@android:color/transparent"/>
                        </shape>
                    </item>
                </layer-list>
            </item>
            <item android:state_selected="false">
                <shape android:shape="rectangle">
                    <solid android:color="@android:color/transparent"/>
                </shape>
            </item>
        </selector>
    </item>
</ripple>

这是我的波纹绘制,我想更改 state_selected solid 颜色。

我尝试过的代码:

RippleDrawable rippleDrawable = (RippleDrawable) textView.getBackground(); // assumes bg is a RippleDrawable
        int[][] states = new int[][]{new int[]{android.R.attr.state_selected}};
        int[] colors = new int[]{R.color.white}; 
        ColorStateList colorStateList = new ColorStateList(states, colors);
        rippleDrawable.setColor(colorStateList);

不幸的是,它不起作用..我缺少什么,这可能是可能的?

您应该在项目中添加ID,以通过Java/Kotlin访问它们。
检查此背景XML文件

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#e0e0e0">
   <item android:id="@+id/fab_shape">
      <shape xmlns:android="http://schemas.android.com/apk/res/android"
         android:shape="rectangle">
         <corners android:radius="25dp" />
        <solid android:color="@color/colorAccent" />
     </shape>
  </item>
</ripple>

要在约束背景上更改此的纯色,将应用此绘制的XML

val background = constraintLayout.background as RippleDrawable
val bgShape = background.findDrawableByLayerId(R.id.fab_shape) as GradientDrawable
bgShape.color = color

用于参考阅读此

这很奇怪。我有一个非常相似的代码,而且效果很好:

val background = textView.background!!.mutate() as RippleDrawable
background.setColor(ColorStateList.valueOf(0xffff0000.toInt()))
textView.background = background

尝试。

我也使功能更容易:

fun View.setBackgroundTintColor(@ColorInt color: Int) {
    val background = background
    if (background is RippleDrawable) {
        val newBackground = background.mutate() as RippleDrawable
        newBackground.setColor(ColorStateList.valueOf(color))
        this.background = newBackground
    } else ViewCompat.setBackgroundTintList(this, ColorStateList.valueOf(color))
}

相关内容

  • 没有找到相关文章

最新更新