在 recyclerView 中,我有一个 imageButton 列表,其中自定义形状应用于所有 ImageButton 的背景。每个 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())));
最佳答案
试试这个:
@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);
}
}
关于android - 如何在 RecyclerView 中设置自定义形状的 ImageButton 的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36387448/