在单个适配器中更改各种ListView项目的颜色

时间:2015-10-07 16:24:56

标签: android listview android-arrayadapter

是否可以在一个ListView

中为不同的ArrayAdapter项设置不同的背景颜色

e.g:

for(int i = 0; i < ArrayAdapter.getCount(); i++){

    Color c;

    switch(i){
         case 0: c = Color.RED; break;
         case 1: c = Color.GREEN; break;
         default: c = Color.BLUE;
    }

    ListView lv = ArrayAdapter.getView(i); //I know this method does not exist  
    lv.setBackgroundColor(c);
}

我不知道怎么管理这个,抱歉我是一个机器人初学者......

2 个答案:

答案 0 :(得分:1)

在适配器的getView中,添加以下代码:

public View getView (int position, View convertView, ViewGroup parent){
    View view = convertView;
    if(view == null){
        // Inflate row view here
    }

    Color c;
     switch(position){
         case 0: c = Color.RED; break;
         case 1: c = Color.GREEN; break;
         default: c = Color.BLUE;
    }

    view.setBackgroundColor(c);
}

答案 1 :(得分:1)

覆盖ArrayAdapter中的getView方法:

public class MyAdapter extends ArrayAdapter<String>{

    public MyAdapter(Context context, int resource) {
        super(context, resource);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v= super.getView(position, convertView, parent);
        v.setBackgroundColor(Color.RED);
        return v;
    }
}