Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/195.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何更改代码中的“纯色”?_Android_Android Layout_Android Xml - Fatal编程技术网

Android 如何更改代码中的“纯色”?

Android 如何更改代码中的“纯色”?,android,android-layout,android-xml,Android,Android Layout,Android Xml,我有一个用xml定义的形状。现在我需要更改代码中的纯色,请您建议如何更改 <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="10dp"> <solid android:color="#000000"/>

我有一个用xml定义的形状。现在我需要更改代码中的纯色,请您建议如何更改

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#000000"/>
    <corners
        android:bottomRightRadius="8dp"
        android:bottomLeftRadius="8dp"
        android:topLeftRadius="0dp"
        android:topRightRadius="0dp"/>
</shape>
我在代码中使用这个

GradientDrawable myGrad = (GradientDrawable)rectangle.getBackground();
myGrad.setColor(Color.BLACK);
希望这有助于:

编辑:对于GradientDrawable而不是ShapeDrawable,我在代码中使用它

GradientDrawable myGrad = (GradientDrawable)rectangle.getBackground();
myGrad.setColor(Color.BLACK);
希望这有助于:


编辑:对于GradientDrawable而不是ShapeDrawable,我在ListView中设置项的背景时遇到了问题。在xml中定义的形状中,我在调用convertview的getBackground方法时遇到了ClassCastException,但是当我调用项的最外层视图的getBackground方法时,异常消失,问题已解决。

我在ListView中设置项的背景时遇到了问题。在xml中定义的形状中,我在调用convertview的getBackground方法时遇到了ClassCastException,但在调用项的最外层视图的getBackground方法时,异常消失,问题解决了。

我得到了ClassCastException,因为GradientDrawable无法转换为ShapeDrawable,但最终我跳过了getPaint方法,只设置了颜色。请修改答案,我会接受。谢谢。08-11 15:08:51.911:E/AndroidRuntime2906:java.lang.ClassCastException:android.graphics.drawable.LayerDrawable无法强制转换为android.graphics.drawable.GradientDrawable,因此不能work@user3111850对于LayerDrawable,不应使用GradientDrawable更改颜色,因为LayerDrawable不是ShapeDrawable的实例,所以我有ClassCastException,因为GradientDrawable不能强制转换为ShapeDrawable,但最后我跳过了getPaint方法,只设置了颜色。请修改答案,我会接受。谢谢。08-11 15:08:51.911:E/AndroidRuntime2906:java.lang.ClassCastException:android.graphics.drawable.LayerDrawable无法强制转换为android.graphics.drawable.GradientDrawable,因此不能work@user3111850对于LayerDrawable,不应使用GradientDrawable更改颜色,因为LayerDrawable不是ShapeDrawable的实例