我正在开发一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,不仅数字20的行获得黄色背景,而且数字0的行(第一行),我不知道为什么会这样.
我在getView方法中做错了什么(比如调用super方法)?我实现的原因是:所有返回的视图应该是相同的(这就是我调用super方法的原因)只有适合if条件的视图才应该更改.
谢谢你的帮助!