我有一个包含各种元素的列表视图,并且会更新很多次。 我想在一些随机位置之后添加一个seprator线,比如在第3个元素,第7个元素,第17个元素,19个元素等之后。
所以我设计了一个包含分隔符的xml文件,并使用自定义SimpleAdapter
在这些位置上对其进行充气。但是,当我运行我的代码时,分隔符被添加到奇怪的位置并使我的列表看起来太丑陋而且某些因素会导致Unfortunately, yourApp has stopped
错误
我以前从未使用过自定义适配器,也不知道我做错了什么。
这是我的简单代码,我添加了注解解释,
public class SpecialAdapter extends SimpleAdapter {
Context context;
private LayoutInflater mInflater;
public SpecialAdapter(Context context, ArrayList<HashMap<String, Object>> newsList, int resource,String[] from, int[] to) {
super(context, newsList, resource, from, to);
this.context = context;
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
// TestApp.endPos holds the positions (it keep changing) after which i want to add
// separator
if (position == TestApp.endPos){
/* my Arraylist is of type HashMap<String, Object>
* I have added an empty element and add the seperator view in
* it.
*/
TestApp.arrayList.add(new HashMap<String, Object>());
// heads is an xml file of my separator
view = mInflater.inflate(R.layout.heads, null);
}
return view;
}
}
任何人都可以帮助我如何简化我的问题以及我做错了什么?
答案 0 :(得分:2)
super.getView
会一次性显示尽可能多的观看次数。稍后它会重新使用它们。
由于您稍后会夸大自己的布局,因此会将其缓存在顶部。最后,super.getView
开始以随机位置返回自定义视图。
要解决这个问题,您需要告诉适配器有两种类型的视图,因此它们可以单独缓存它们。
以下是示例方法(未经测试但应该有效):
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position == TestApp.endPos) {
// Handle separator views manually
TestApp.arrayList.add(new HashMap<String, Object>());
// If separator is not yet cached, create the view
if (convertView == null) {
convertView = mInflater.inflate(R.layout.heads, null);
}
} else {
// Normal views are handled by the adapter
convertView = super.getView(position, convertView, parent);
}
return convertView;
}
@Override
public int getViewTypeCount() {
// There are 2 types: separator and normal
return 2;
}
@Override
public int getItemViewType(int position) {
if (position == TestApp.endPos) {
// Separator view
return 0;
} else {
// Normal view
return 1;
}
}
注意:有两种类型,意味着将缓存和重复使用两种类型的视图。
答案 1 :(得分:0)
在getView
方法中,您应确定是否要使用seperator
视图,然后为该项目的视图充气:
if (view == null) {
if (showSeperatorItem)
view = _activity.getLayoutInflater().inflate(R.layout.item__row_layout_with_seperator, parent, false);
else
view = _activity.getLayoutInflater().inflate(R.layout.item__row_layout, parent, false);
}