androidgridviewandroid-resourcesstatelistdrawable

How to use a StateListDrawable at runtime?


I have a problem with some code. I want to create a ColorPicker DialogFragment. At the moment I use a GridView and a custom BaseAdapter to show some color shapes. For each color I use a round ShapeDrawable. To set the color of the default state, I use the following code:

getView() of my "ColorAdapter"

ImageView imageView;
if (convertView == null) {  
    imageView = new ImageView(ctx);
    imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setPadding(8, 8, 8, 8);
} else {
    imageView = (ImageView) convertView;
}

Drawable drawable = ctx.getResources().getDrawable(R.drawable.color_item);
imageView.setBackground(drawable);

StateListDrawable states = (StateListDrawable) imageView.getBackground();

GradientDrawable shape = (GradientDrawable) states.getCurrent();
shape.setColor(colors[i]);

return imageView;

That works fine for me.

But I want to change the color of an icon, when it is pressed. So I use a StateListDrawable.

<selector xmlns:android="http://schemas.android.com/apk/res/android" 
     android:constantSize="true" >

     <item 
          android:state_pressed="true"
          android:drawable="@drawable/circle" />
     <item
          android:drawable="@drawable/circle" />

</selector>

But, because I have different colors for each entry in the GridView, I have to change the color of the state at runtime.

As you can see I use the same drawable resource for both states. Maybe I can set the color of one state, as I do it with states.getCurrent()?

I have also tried to use a ColorFilter to decrease the brightness level. But when I try to do that, the ImageView is always black, when it`s pressed.

Does anybody know how to do that?


Solution

  • Ok, I found a solution. I use a LayerDrawable with two layers, the first one contains my shape, the second one a StateListDrawable. This StateListDrawable contains one empty shape for default state and one grey shape with lower alpha value. So now, when I press my color circle, the grey shape is put over my color shape.