2012-08-15 154 views
3

是否可以在自定义适配器中设置ListView/ExpandableListView的backgroundResourcebackgroundColorAndroid设置背景资源和颜色

我有一个透明PNG,将作为可扩展列表视图中的每一行的边框。这个图像只是一个内部阴影和底部的边界。

我们的目标是做这样的事情:

png + color

当我设置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; 
} 

回答

7

setBackgroundResourcesetBackgroundColor都在内部使用相同的API setBackgroundDrawable来完成他们的任务。所以一个覆盖另一个。所以你无法用这个api来实现你的目标。

你将不得不使用setBackgroundResource使用自定义绘制

+0

我真的这样做,查看色的最佳组合在我的程序中。我在Photoshop中嘲笑的东西并没有在设备上渲染,所以我想找到一种简单/快速的方式来改变颜色,而不必重新编写.9.png文件。但是我最终使用了一个图层列表,然后设置drawable。 – meepz 2012-08-15 23:39:00

1

有是肯定的代码可以采取的背景绘制和使用涂料就可以了一些色彩。但我现在不能重新注册:-)
但是还有其他方法可以实现您的目标。看看这个网站:
http://developer.android.com/guide/topics/resources/drawable-resource.html
看看9patch可绘制的,你可以准备,这将只有小图像,将收缩/扩大根据需要。你准备一个和其他颜色里面。
第二种方法是使用ShapeDrawable。在XML中,您可以在其中创建矩形和一些纯色。
在这两种情况下,只需根据需要交换背景可绘制对象。
我不明白你想要什么,但我希望这可以帮助。

4

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

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