在recyclerView中,我有一个imageButtons列表,其中自定义形状应用为所有ImageButtons的背景。每个ImageButton目前都有一个颜色列表中的纯色:colors[]
这就是现在的样子:
我想将icon.png放在索引0(棕色按钮)的位置而不是纯色。到目前为止,我已经用了很多天试图找到一个解决方案,但没有任何咒语。
以下是所有相关代码:
这是设置颜色的recyclerView适配器中的代码:
Resources resources = App.getAppContext().getResources();
String colors[] = resources.getStringArray(R.array.backgroundcolors);
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Drawable drawable = holder.colorButton.getBackground();
//This is here where each ImageButton gets a color from the colorlist colors[]
if (drawable instanceof GradientDrawable) {
GradientDrawable gd = (GradientDrawable) drawable.getCurrent();
gd.setColor(Color.parseColor(colors[position]));
//This does nothing
} else if (drawable instanceof RippleDrawable) {
RippleDrawable rd = (RippleDrawable) drawable;
int color = Color.parseColor(colors[position]);
rd.setColor(newColorStateList(color));
}
}
每个imageButton的colorStatList代码:
private static ColorStateList newColorStateList(int color) {
int[][] states = new int[][]{
new int[]{android.R.attr.state_enabled}, // enabled
new int[]{-android.R.attr.state_enabled}, // disabled
};
int[] colors = new int[]{
color, color
};
return new ColorStateList(states, colors);
}
我的RecyclerView适配器的自定义按钮:
public class ColorButton{
private ImageButton button;
private String color;
public static List<ColorButton> colorButtonList;
public ColorButton(ImageButton button, String color) {
this.button = button;
this.color = color;
}
static ColorButton colorButton = new ColorButton(new ImageButton(App.getAppContext()), null);
public static List<ColorButton> initColorButtons(){
colorButtonList = new ArrayList<>();
Resources resources = App.getAppContext().getResources();
String colors[] = resources.getStringArray(R.array.backgroundcolors);
for(int i=0; i<colors.length; i++){
colorButtonList.add(new ColorButton(new ImageButton(App.getAppContext()), colors[i]));
}
return colorButtonList;
}
你可能想知道我为什么String color;
这是用于在用户点击颜色按钮时设置应用的背景颜色:mEditText.setBackgroundColor(Color.parseColor((mColorButtons.get(position).getColor())));
答案 0 :(得分:3)
试试这个:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position ==0){
holder.colorButton.setBackgroundResource(R.drawable.colorpicker2);
}
else
{
GradientDrawable gd = context.getResources().getDrawable(R.drawable.bbshape);
gd.setColor(Color.parseColor(colors[position]));
holder.colorButton.setBackGroundDrawable(gd);
}
}