setColor method of GradientDrawable drawing different color

Gokhan Arik picture Gokhan Arik · Jun 6, 2013 · Viewed 8.8k times · Source

I have a shape in layer-list and my goal is to change color of the shape programmatically at runtime. I have String for HEX code and I used Color.parseColor() to parse it and I passed to setColor method. Whenever I run the application it shows different color then I expect.

Here is my code for XML file :

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >


<item 
    android:id="@+id/lvbg"
    android:top="1dp">
    <shape
        android:id="@+id/listview_background"
        android:shape="rectangle" >
        <size
            android:height="220dp"
            android:width="600dp" >
        </size>

        <solid android:color="@android:color/black"></solid>

        <corners android:radius="15dp" />
    </shape>
</item>
</layer-list>

And this is my code in CustomAdapter :

convertView = mInflater.inflate(R.layout.student_info_selection_fragment_icon, null);
holder = new ViewHolder();
holder.collegeBG=(LayerDrawable)convertView.getResources().getDrawable(R.drawable.rectangle);
holder.bg = (GradientDrawable)holder.collegeBG.findDrawableByLayerId(R.id.lvbg);
String color = "#FF" + rowItem.getCollegeColor();
holder.bg.setColor(Color.parseColor(color));

For example when I put #FF1D0A63 I get black or brown, totally different colors. Thanks

Answer

Gokhan Arik picture Gokhan Arik · Jun 7, 2013

I still don't know what the problem is but I realized that when I use layer-list in xml and assign it as background to a view, and try to change color of a shape in layer-list I am having this problem.

So I solved it separating my background shape from layer-list.

I put my background shape to another file :

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listview_background"
    android:shape="rectangle" >

    <size
        android:height="220dp"
        android:width="600dp" >
    </size>
    <solid android:color="@android:color/black" > </solid>
    <corners android:radius="15dp" />

</shape>

And I assigned it as a background to a TextView.

The reason I used layer-list was to combine 2-3 shapes and make them gradient and give them rounded corners. Instead I used View and TextView and assigned shapes to them as background and it worked.

Here is my new CustomAdapter:

convertView = mInflater.inflate(R.layout.student_info_selection_fragment_icon, null);
holder = new ViewHolder();
holder.tvBackground = (TextView) convertView.findViewById(R.id.tvSelectionCollegeBackground);
GradientDrawable background = (GradientDrawable) holder.tvBackground.getBackground();


String color = "#FF" + rowItem.getCollegeColor();
background.setColor(Color.parseColor(color));
holder.tvBackground.setBackground(background);