适配器出了问题

时间:2015-07-03 12:49:42

标签: java android

我有下一个适配器:

public class CityAdapter extends ArrayAdapter<String> {     

    public CityAdapter(Context context, int resource) {
        super(context, resource, Cities.TITLES);

    }    

    public int getCount() {
       return Cities.ARRAY.length;
    }

    @SuppressLint("InflateParams")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {    
        View v = convertView;    
        if (v == null) {    
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.city_list_row, null);    
        }

        TextView title = (TextView) v.findViewById(R.id.cityTitle);    
        title.setText(Cities.ARRAY[position].getName());    
        if (position==4) {    
            title.setTextColor(Color.parseColor("#ff0000"));
        }    
        return v;    
    }    
}

请仔细看看这一行:

if (position==4) 

我不知道怎么做,但该声明也适用于0号位置。

enter image description here

似乎真的不可能。怎么了?如果我像这样更改我的代码:

if (position==4) {
    title.setText("hey!!!");
    title.setTextColor(Color.parseColor("#ff0000"));
}

我会得到这个:enter image description here

2 个答案:

答案 0 :(得分:1)

为您的颜色设置添加其他案例

if (position==4) {    
    title.setTextColor(Color.parseColor("#ff0000"));
} 
else {
    title.setTextColor(Color.parseColor("#ffffff"));
}

答案 1 :(得分:1)

您没有实施其他部分。

ViewHolder holder;
if (v == null) {    
    LayoutInflater vi;
    vi = LayoutInflater.from(getContext());
    v = vi.inflate(R.layout.city_list_row, null);   
    holder.title = (TextView) v.findViewById(R.id.cityTitle); 
    v.setTag(holder); 
} else {
    holder = (ViewHolder) convertView.getTag();
}

然后你需要创建一个类

class ViewHolder {
    TextView title;
}

此外,你还需要其他部分。

if (position==4) {
    title.setText("hey!!!");
    title.setTextColor(Color.parseColor("#ff0000"));
}else{
 title.setText("heyfffgg!!!");
    title.setTextColor(Color.parseColor("#ff0000"));
}