我正在尝试使用KitKat上随机生成的颜色创建ListView 问题:它只显示不同项目的相同颜色 这是我的代码:
Drawable d = getResources().getDrawable(R.drawable.main_item_image_background);
int r = (int) (Math.random() * 256);
int g = (int) (Math.random() * 256);
int b = (int) (Math.random() * 256);
int randColor = Color.argb(255, r, g, b);
d.setColorFilter(new PorterDuffColorFilter(randColor, PorterDuff.Mode.SRC_IN));
viewHolder.ivLogoBackground.setImageDrawable(d);
我也试过这样做:
Random rand = new Random();
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
它在Lollipop或更高版本上运行良好但在KitKat上它显示每个项目的相同颜色。
我认为问题出在d.setColorFilter(new PorterDuffColorFilter(randColor, PorterDuff.Mode.SRC_IN));
Android M:
Android KitKat:
解决方案: Drawable
必须采用mutate()
方法。然后列表项中的图像将是不同的颜色:)
答案 0 :(得分:0)
///适配器类
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.CustomViewHolder> {
private ColorGenerator generator;
private Activity mActivity;
private ArrayList<String> iDataList;
public TestAdapter(Activity activity, ArrayList<String> countryList, int limit, boolean isLiveCountry) {
this.mActivity = activity;
generator = ColorGenerator.MATERIAL;
}
@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item, parent, false);
return new CustomViewHolder(view);
}
@Override
public void onBindViewHolder(CustomViewHolder holder, final int position) {
int color = generator.getRandomColor();
holder.view.setBackgroundColor(color);
}
@Override
public int getItemCount() {
return iDataList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
private View view;
public CustomViewHolder(View itemView) {
super(itemView);
view = itemView.findViewById(R.id.view);
}
}
}
//颜色生成器
public class ColorGenerator {
public static ColorGenerator DEFAULT;
public static ColorGenerator MATERIAL;
static {
DEFAULT = create(Arrays.asList(
0xfff16364,
0xfff58559,
0xfff9a43e,
0xffe4c62e,
0xff67bf74,
0xff59a2be,
0xff2093cd,
0xffad62a7,
0xff805781
));
MATERIAL = create(Arrays.asList(
0xffe57373,
0xfff06292,
0xffba68c8,
0xff9575cd,
0xff7986cb,
0xff64b5f6,
0xff4fc3f7,
0xff4dd0e1,
0xff4db6ac,
0xff81c784,
0xffaed581,
0xffff8a65,
0xffd4e157,
0xffffd54f,
0xffffb74d,
0xffa1887f,
0xff90a4ae
));
}
private final List<Integer> mColors;
private final Random mRandom;
public static ColorGenerator create(List<Integer> colorList) {
return new ColorGenerator(colorList);
}
private ColorGenerator(List<Integer> colorList) {
mColors = colorList;
mRandom = new Random(System.currentTimeMillis());
}
public int getRandomColor() {
return mColors.get(mRandom.nextInt(mColors.size()));
}
public int getColor(Object key) {
return mColors.get(Math.abs(key.hashCode()) % mColors.size());
}