将setIcon设置为ColorDrawable的首选项在Android 5.0 Lollipop上不起作用 [英] Preference setIcon to ColorDrawable does not work on Android 5.0 Lollipop

查看:81
本文介绍了将setIcon设置为ColorDrawable的首选项在Android 5.0 Lollipop上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我使用以下行来区分某些首选项:

In my app I use the following line to distinguish some preferences:

preference.setIcon(new ColorDrawable(color));

在Lollipop之前的Android版本中,它可以正常工作,并且首选项会显示所选颜色的方形图标,但在Lollipop中则不会显示.

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?

谢谢

以下是对我有用的解决方案:

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);
}  

推荐答案

这里是Matrix答案的简化版本,我删除了对该版本的检查,因为它在Ice Cream Sandwich上也无法正常工作(细线为显示,而不是正方形):

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);
}

这篇关于将setIcon设置为ColorDrawable的首选项在Android 5.0 Lollipop上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆