1

我创建了自定义列表视图,每一行看起来都像我的文件 custom_row.xml。有什么办法,如何分别为每一行设置不同的背景颜色(我需要设置它,因为我的行可以有不同的值)。

感谢您的任何想法

4

3 回答 3

2

由于您在为 custom_row.xml 充气后在 getView 方法中执行自定义列表视图,因此更改了 inflate 方法的返回视图的背景。请参阅下面的示例片段:

public getView(int position, View convertView, ViewGroup parent) {
       convertView = getLayoutInflater().inflate(R.layout.custom_xml, null);
       do some stuff...

       //let say you have an arraylist of color
       convertView.setBackgroundColor(arraylist.get(position));

       //in case that your color is limited, just re-use your color again
       //and some logic how to re-use the colors.
}
于 2012-04-18T16:52:03.030 回答
1

在此处使用其他答案会阻止选择器正常工作,并且选择器停止完全突出显示行。通过按照接受的答案中的描述手动设置颜色,选择器在滚动时停止突出显示行。因此,让我描述一个不会弄乱您的选择器的解决方案。

这篇文章描述了如何用透明度来解决这个问题,但我无法真正让它发挥作用。所以我的解决方案是我的可绘制文件夹中有两个列表选择器。这样我可以在运行时设置两种不同的背景颜色并保持选择器工作。

list_selector_darkgrey.xml 用于我的深灰色线

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/gradient_bg_darkgrey" android:state_pressed="false" android:state_selected="false"/>
<item android:drawable="@drawable/gradient_bg_hover" android:state_pressed="true"/>
<item android:drawable="@drawable/gradient_bg_hover" android:state_pressed="false" android:state_selected="true"/>
</selector>

和 list_selector.xml 为浅灰色线

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/gradient_bg" android:state_pressed="false" android:state_selected="false"/>
<item android:drawable="@drawable/gradient_bg_hover" android:state_pressed="true"/>
<item android:drawable="@drawable/gradient_bg_hover" android:state_pressed="false" android:state_selected="true"/>
</selector>

请忽略drawable中的渐变,您可以将其替换为您的颜色。

在 BaseAdapter 类中,我将调用 setBackgroundResource 以将一些行显示为浅灰色,将其他行显示为深灰色。选择器颜色相同,并在 XML 文件中定义。

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;

    if (convertView == null)
        vi = inflater.inflate(R.layout.list_row, null);

             ... some logic ...

    if (... some condition ...) {
        vi.setBackgroundResource(R.drawable.list_selector_darkgrey);
    }
    else { 
        vi.setBackgroundResource(R.drawable.list_selector);
    }
    return vi;
}
于 2012-11-04T05:46:12.520 回答
1

在适配器中,您可以在使用 getView 方法检索视图时手动设置视图的背景颜色。

    // set the background to green
    v.setBackgroundColor(Color.GREEN);
于 2012-04-18T16:34:04.033 回答