【发布时间】:2016-04-04 04:19:04
【问题描述】:
在 recyclerView 中,我有一个带有自定义形状的 imageButtons 列表,该列表应用为所有 ImageButtons 的背景。每个 ImageButton 当前都有一个颜色列表中的纯色:colors[]
现在是这样的:
我想在索引 0(棕色按钮)的位置放置一个 icon.png,而不是纯色。到目前为止,我已经用了很多天试图自己找到解决方案,但没有任何成功。
这里是所有相关代码:
这是 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())));
【问题讨论】:
-
如果您使用 ImageButton,则 xml 中有两个属性:
background- 应用您自己的形状,但将该形状中的颜色设置为透明 (alpha=0),以及src属性 -> 这里可以设置图片
标签: android android-recyclerview