How to change `solid color` from the code?

半腔热情 提交于 2019-12-18 18:47:47

问题


I have a Shape defined in xml. Now I need to change a solid color from the code, could you please advice how?

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

回答1:


I use this in my code

GradientDrawable myGrad = (GradientDrawable)rectangle.getBackground();
myGrad.setColor(Color.BLACK);

Hope this helps :)

EDIT: for GradientDrawable instead of ShapeDrawable




回答2:


I met the problem when I set the background of the item(in the listview)the shape defined in xml, I've got ClassCastException when I invoke the convertview's getBackground() method, but when I invoke the item's outest view's getBackground() method,the Exception disappear, the problem resolved.



来源:https://stackoverflow.com/questions/16775891/how-to-change-solid-color-from-the-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!