首选项 setIcon 到 ColorDrawable 在 Android 5.0 Lollipop 上不起作用

The*_*rix 5 android android-preferences

在我的应用程序中,我使用以下行来区分一些偏好:

preference.setIcon(new ColorDrawable(color));
Run Code Online (Sandbox Code Playgroud)

在 Lollipop 之前的 Android 版本中它工作正常并且首选项显示所选颜色的方形图标,但在 Lollipop 中没有显示。

关于如何解决它的任何想法?

谢谢

这是一个对我有用的解决方案:

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);
}  
Run Code Online (Sandbox Code Playgroud)

Yoa*_*uet 0

这是《黑客帝国》答案的简化版本,我删除了对该版本的检查,因为它在冰淇淋三明治上也无法正常工作(显示了一条细线,而不是正方形):

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);
}
Run Code Online (Sandbox Code Playgroud)