如何更改波纹状可绘制对象的纯色

如何更改波纹状可绘制对象的纯色

本文介绍了如何更改波纹状可绘制对象的纯色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?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 纯色颜色.

here is my ripple drawable and i want to change the state_selected, solid color.

我尝试过的代码:

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);

不幸的是,它不起作用.我想念什么,这可能吗?

unfortuantely it doesn't work.. what am I missing and is this possible?

推荐答案

您应在项目中添加一个ID,以通过Java/kotlin访问它们.
检查此背景XML文件

You should add an id to items to access them via java/kotlin.
check this background XML file

<?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>

要更改其纯色,请在constraintLayout背景上应用此可绘制的XML

to change the solid color of this, on constraintLayout background, this drawable XML is applied

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

供参考阅读

这篇关于如何更改波纹状可绘制对象的纯色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 13:29