SetIcon preference for ColorDrawable not working on Android 5.0 Lollipop

In my application, I use the following line to distinguish some settings:

preference.setIcon(new ColorDrawable(color));

In Android versions prior to Lollipop, it works fine, and preference shows a square icon of the selected color, but it does not appear in Lollipop.

Any idea how to solve it?

thank

Here is a solution that works for me:

preference.setIcon(getPreferenceIcon(color));

function Drawable getPreferenceIcon(int color)
{
  if (Build.VERSION.SDK_INT < 21) return new ColorDrawable(color);
  int bitmap_size = 64;
  Bitmap bitmap = Bitmap.createBitmap(bitmap_size, bitmap_size, Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);
  Paint paint = new Paint();
  paint.setColor(color);
  canvas.drawRect(new Rect(0, 0, bitmap_size, bitmap_size), paint);
  return new BitmapDrawable(getResources(), bitmap);
}  
+4
source share
1 answer

Here is a simplified version of the Matrix answer, I removed the version check, since it also did not work properly on Ice Cream Sandwich (a thin line was shown, not a square):

private Drawable getPreferenceIcon(int color) {
    int size = 200;// Set to a big size to fit all screens, will be contained anyway in the preference row
    Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    bitmap.eraseColor(color);

    return new BitmapDrawable(getResources(), bitmap);
}
0
source

All Articles