Preference setIcon to ColorDrawable does not work on Android 5.0 Lollipop

扶醉桌前 提交于 2019-12-23 13:14:21

问题


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

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