为什么我不能动态设置自定义Listview项目的背景?

时间:2011-06-16 14:24:24

标签: android listview

我有自定义列表视图,我使用自定义listadapter来显示该列表。在我的自定义listadapter中,我试图根据对象中的值动态设置每个项目的颜色。然而,每当我尝试这样做时,项目都会变淡,而不是获得它们设置的颜色。我正在为项目应用一些样式但是当我删除它们的效果时它仍然无效。这是我更改每个项目背景颜色的代码:

    private class stationAdapter extends ArrayAdapter<Station>{
    private ArrayList<Station> stations;

    public stationAdapter(Context context, int textViewResourceId, ArrayList<Station> stations) {
        super(context, textViewResourceId, stations);
        this.stations = stations;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
        }
        Station temp = stations.get(position);
        if (temp != null) {
            TextView stationName = (TextView) v.findViewById(R.id.stationname);
            TextView serviced = (TextView) v.findViewById(R.id.inservice);

            try{
                if(temp.getLine().equals("red")){
                    v.setBackgroundColor(R.color.red);

                }
                else{
                    v.setBackgroundColor(R.color.green);
                }
            }catch(Exception e){
                Log.d(TAG, "Null pointer");
            }
            if (stationName != null) {
                stationName.setText("Station: "+temp.getName());                            }
            if(serviced != null){
                serviced.setText("In Service: "+ temp.getInServive());
            }
        }
        return v;
    }

}

如果有人能够指出我做错了什么,我会非常感激。

3 个答案:

答案 0 :(得分:3)

您无法使用setBackgroundColor然后引用资源。如果你想使用setBackgroundColor(),你需要使用Color类,如:

setBackgroundColor(Color.BLACK);

相反,如果你想设置一个资源(R.drawable,R.color等...)你需要像

那样做
v.setBackgroundResource(R.color.black);

修改

如果项目在滚动列表时开始变为灰色,则需要缓存颜色提示。如果要向项目和列表添加自定义背景,则需要将其设置为透明色。

答案 1 :(得分:2)

就像Darko提到的那样,你正在尝试设置一种颜色,而是使用资源ID。话虽如此,使用纯色作为列表项背景是一个很大的禁忌,你绝对想要使用选择器:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="false" android:state_pressed="false" android:state_selected="false"
        android:state_checked="false" android:state_enabled="true" android:state_checkable="false"
        android:drawable="@color/red" />
</selector>

将其放入drawables文件夹中的list_red_background.xml并改为使用setBackgroundResource()

答案 2 :(得分:0)

你有没有关闭淡出?

http://developer.android.com/resources/articles/listview-backgrounds.html

将其添加到ListView布局文件中:

android:cacheColorHint="#00000000"