问题
In my app I use the following line to distinguish some preferences:
preference.setIcon(new ColorDrawable(color));
In Android versions prior to Lollipop it works fine and the preference shows a square icon of the selected color, but in Lollipop none is shown.
Any idea for how to solve it?
Thanks
Here is a solution that is working 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);
}
回答1:
Here is a simplified version of The Matrix's answer, I removed the check on the version since it was also not working properly on Ice Cream Sandwich (a thin line was displayed, 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);
}
来源:https://stackoverflow.com/questions/27401278/preference-seticon-to-colordrawable-does-not-work-on-android-5-0-lollipop