Android ListView背景颜色总是显示灰色

9
我有一个ListView,我正在使用自定义ListAdapter填充它。在适配器中(在getView(int, View, ViewGroup)方法中),我使用setBackgroundColor(int)设置View的背景颜色。问题是,无论我将背景设置为什么颜色,它始终是深灰色。值得注意的是,我正在使用浅色主题。
相关(简化)代码如下:

AndroidManifest.xml:

<activity 
    android:name=".MyActivity"
    android:theme="@android:style/Theme.Light" />

MyAdapter.java:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    View av = inflater.inflate(R.layout.my_row, parent, false);
    av.setBackgroundColor(R.color.myRow_red);
    mName = (TextView) av.findViewById(R.id.myRow_name);
    mName.setText("This is a name");
    return av;
}

任何想法/建议?
6个回答

21
你应该使用以下代码:setBackgroundResource(R.color.myRow_red) 而不是 setBackgroundColor()。在你的示例中,背景颜色是通过ID分配的而不是资源中描述的实际颜色。

我有类似的情况,但我不能在形状上使用这个解决方案。我在这里提出了一个更详细的问题:http://stackoverflow.com/questions/39820240/android-canvas-drawrect-colour-always-shows-as-grey - ScreenSeer

6

您必须将cacheColorHint属性设置为所需的列表背景颜色。这是一种必要的解决方案,以考虑Android在列表上执行的绘图优化。

请参见此处:链接文本


没错,如果你不需要动态地改变背景颜色,你可以在你的my_row.xml布局文件中添加android:background="#FF0000"。 - Dimitar Dimitrov
midj:在我的情况下,实际上并不是这样的,你只是看到一个超级简化的例子。 - Jeremy Logan
@fiXedd:那你的问题是什么?禁用颜色缓存没有帮助吗? - mxk

2

我遇到了类似的问题,分隔线显示为灰色。我发现其他解决方案都没有效果,但是在我的ListView上使用android:divider="<drawable,color, or whatever>"有效。


0

请尝试这个:

setBackgroundColor(0xFF5DB9FB);

0
尝试像这样做:

av.setBackgroundColor(getResources().getColor(R.color.myRow_red));


0
你可以将整个行包装在另一个视图中,并在该视图上设置背景颜色。这个视图将是该行的第一个(也是唯一的)子视图。

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