我正在开发一个 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 条件的视图才应该改变。
感谢您的帮助!
我做了一些研究来找出如何正确地完成此操作。
我正在为其他有同样问题的人写下这个,因为我想这是正确的方法。如果我弄错了或者这个解决方案有任何我没有看到的缺陷,请告诉我。
public class WeightListAdapter extends ArrayAdapter<Integer> {
private static final int TYPE_COUNT = 2;
private static final int TYPE_ITEM_COLORED = 1;
private static final int TYPE_ITEM_NORMAL = 0;
public WeightListAdapter(Context context, List<Integer> objects) {
super(context, android.R.layout.simple_list_item_1, objects);
}
@Override
public int getViewTypeCount() {
return TYPE_COUNT;
}
@Override
public int getItemViewType(int position) {
int item = getItem(position);
return (item == 30) ? TYPE_ITEM_COLORED : TYPE_ITEM_NORMAL;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
switch (getItemViewType(position)) {
case TYPE_ITEM_COLORED:
v.setBackgroundColor(Color.YELLOW);
break;
case TYPE_ITEM_NORMAL:
break;
}
return v;
}
}
显然基类已经实现了确保正确的逻辑convertView
被传递到getView
方法(基于getViewItemType
and getViewTypeCount
方法)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)