我正在开发一个 ListActivity,它将显示一堆数字(权重)。我想更改 ListView 中特定行的背景。为此,我创建了 ArrayAdapter 类的自定义实现并覆盖了 getView 方法。适配器接受数字列表并将数字为 20 的行的背景设置为黄色(为简单起见)。
public class WeightListAdapter extends ArrayAdapter<Integer> {
private List<Integer> mWeights;
public WeightListAdapter(Context context, List<Integer> objects) {
super(context, android.R.layout.simple_list_item_1, objects);
mWeights = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
int itemWeight = mWeights.get(position);
if (itemWeight == 20) {
v.setBackgroundColor(Color.YELLOW);
}
return v;
}
}
问题在于,不仅编号为 20 的行获得黄色背景,而且编号为 0 的行(即第一行)也是如此,我不确定为什么会这样。
我在 getView 方法中做错了什么(比如调用 super 方法)?我对实现的理由是:所有返回的视图应该是相同的(这就是我调用 super 方法的原因)只有符合 if 条件的视图应该被更改。
谢谢你的帮助!