安卓如何设置背景颜色和资源

4
在自定义适配器中,是否可以设置ListView/ExpandableListView的backgroundResource和backgroundColor?我有一个透明的png图片,作为可扩展列表视图中每一行的边框。这个图片只是一个内阴影和底部的边框。目标是做出下面这样的效果:当我设置了backgroundResource和backgroundColor时,只有其中一个显示出来,我无法让资源覆盖颜色。有人知道是否可能吗?以下是我的代码,以更好地了解情况:
private int[] colors2= new int[] { Color.parseColor("#e2e8e9"), Color.parseColor("#f1f2f2") };
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    ViewHolder holder;
    ExpandListGroup group = (ExpandListGroup) getGroup(groupPosition);
    if (convertView == null) {
        holder = new ViewHolder();
        LayoutInflater inf = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        convertView = inf.inflate(R.layout.expandlist_group_item, null);
        holder.title = (TextView) convertView.findViewById(R.id.tvGroup);
        convertView.setTag(holder);
    }else{
        holder = (ViewHolder) convertView.getTag();
    }
    int colorPos = groupPosition % colors.length; 
    convertView.setBackgroundResource(R.drawable.row_forground);
    convertView.setBackgroundColor(color2[colorPos]);
    holder.title.setText(group.getName());
    return convertView;
}
4个回答

10

setBackgroundResourcesetBackgroundColor都使用相同的API setBackgroundDrawable来完成它们的任务。因此,一个会覆盖另一个。所以你不能使用这个API来实现你的目标。

你需要使用自定义的drawable来使用setBackgroundResource


我这么做是为了找到程序中最佳颜色组合。在Photoshop中模拟的效果与设备上的渲染不同,因此我想找到一种简单/快速的方法来更改颜色,而不必重新制作.9.png文件。但最终我使用了一个图层列表,然后将可绘制对象设置为该列表。 - meepz

5

如果您想使用setBackgroundResourcesetBackgroundColor,可以这样做:

...
int colorPos = groupPosition % colors.length;
convertView.setBackgroundResource(R.drawable.row_forground);
GradientDrawable drawable = (GradientDrawable) convertView.getBackground();
drawable.setColor(color2[colorPos]);
...

我遇到了这个异常java.lang.ClassCastException: android.graphics.drawable.BitmapDrawable无法转换为android.graphics.drawable.GradientDrawable。 - BHA Bilel

1

肯定有代码可以获取背景可绘制对象并在其上涂上一些颜色。但我现在记不清了 :-)
但是还有其他方法可以实现您的目标。看看这个网站:
http://developer.android.com/guide/topics/resources/drawable-resource.html
查看您可以准备的9patch可绘制对象,它们将仅是需要时缩小/扩展的小图像。您可以在其中一个内部准备另一种颜色。
第二种方法是使用ShapeDrawable。在XML中,您创建矩形并在其中填充一些纯色。
在这两种情况下,您只需根据需要交换背景可绘制对象即可。
我不明白您想要实现什么,但我希望这可以帮助到您。


0
只需在将背景资源设置为视图后添加ColorFilter,就像这样。
view.setBackgroundResource(R.drawable.yourRessource);
view.getBackground().setColorFilter(
                Color.yourColor,
                PorterDuff.Mode.DST_OVER
);

了解更多关于使用Android的ColorFilter操作图像和Drawable的内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接