有条件地更改列表视图行的背景颜色

时间:2013-11-11 16:32:43

标签: java android listview android-listview baseadapter

我正在尝试根据参数和行View v = super.getView(position, convertView, parent)更改列表视图的背景行颜色,它给出了错误“无法直接调用抽象方法getView(int,View,ViewGroup)对于类型适配器“。这是所有代码。

public class CustomListViewAdapter extends BaseAdapter
{  

LayoutInflater inflater;
List<ListViewItem> items;

public CustomListViewAdapter(Activity context, List<ListViewItem> items) {  
    super();

    this.items = items;
    this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override  
public int getCount() {  
    // TODO Auto-generated method stub  
    return items.size();  
}  

@Override  
public Object getItem(int position) {  
    // TODO Auto-generated method stub  
    return null;  
}  

@Override  
public long getItemId(int position) {  
    // TODO Auto-generated method stub  
    return 0;  
}

@Override  
public View getView(final int position, View convertView, ViewGroup parent) {  
    View v = super.getView(position, convertView, parent); 

    ListViewItem item = items.get(position);

    if(convertView==null)
        v = inflater.inflate(R.layout.my_hospitals, null);
        TextView status = (TextView) v.findViewById(R.id.status);
        TextView name = (TextView) v.findViewById(R.id.name);
        TextView table = (TextView) v.findViewById(R.id.id);
        TextView info = (TextView) v.findViewById(R.id.info);

        status.setText(item.status);
        name.setText(item.name);
        table.setText(item.table);
        info.setText(item.info);

        if (item.status == "green"){
            v.setBackgroundColor(Color.GREEN);
        }

    return v;  
}
}

3 个答案:

答案 0 :(得分:1)

更改getView()

@Override  
public View getView(final int position, View convertView, ViewGroup parent) {  
    View v=convertView;
    ListViewItem item = items.get(position);

    if(v==null){
        v = inflater.inflate(R.layout.my_hospitals, null);
    }
        TextView status = (TextView) v.findViewById(R.id.status);
        TextView name = (TextView) v.findViewById(R.id.name);
        TextView table = (TextView) v.findViewById(R.id.id);
        TextView info = (TextView) v.findViewById(R.id.info);

        status.setText(item.status);
        name.setText(item.name);
        table.setText(item.table);
        info.setText(item.info);     
        String state=tem.status;


        if (state.equals("green"){
            v.setBackgroundColor(Color.GREEN);
        }

    return v;  
}

答案 1 :(得分:0)

好像错误说你不能这样做

View v = super.getView(position, convertView, parent);
相反,你应该做

View v = convertView;

然后检查v是否为空

if(v == null){
    //get the view
}

答案 2 :(得分:0)

也许我不太了解你的问题,而不是这个

item.status == "green"

使用此

  

item.status.equals( “绿”)