我目前正在使用一个非常简单的ListView,最多可以使用2种不同的视图类型。为了使一切顺利,我尝试回收视图。我的代码现在是:
@Override
public int getItemViewType (int position){
if(mHasBefore&&position==0){
return TYPE_PAGER;
}else if(mHasNext&&position==getCount()-1){
return TYPE_PAGER;
}else return TYPE_SCORE;
}
@Override
public int getViewTypeCount (){
return 1+((mHasBefore==true||mHasNext==true)?1:0);
}@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("outa","View: pos: "+position+ " . "+getItemViewType(position)+" - "+getViewTypeCount());
if(getItemViewType(position)==TYPE_SCORE)return getScoreView(position,convertView,parent);
else return getPagerView(position,convertView,parent);
}
protected View getPagerView(int position,View convertView,ViewGroup parent){
if (convertView == null){
convertView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.listitem_highscore_pager, null);}}
protected View getScoreView(int position,View convertView,ViewGroup parent){
if (convertView == null){
convertView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.listitem_highscore, null);}}
基本上它应该在最后一个项目上显示不同的视图,但它仍然显示默认项目,即使LogCat声明它在getView()中不是TYPE_SCORE。因此convertView确实提供了可回收的视图。我做错了什么或者这是正常行为吗?
答案 0 :(得分:5)
你走了:
private static final int TYPE_PAGER = 0;
private static final int TYPE_PAGER = 1;
private static final int VIEW_COUNT = 2;
private LayoutInflater mInflater = LayoutInflater.from(context);
@Override
public int getViewTypeCount (){
return VIEW_COUNT;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
ViewHolder2 holder2;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
holder2 = new ViewHolder2();
switch(type){
case TYPE_SCORE:
Log.i(TAG, "ConvertView type1");
convertView = mInflater.inflate(R.layout.listitem_highscore, null);
convertView.setTag(R.layout.listitem_highscore, holder);
break;
case TYPE_PAGER:
Log.i(TAG, "ConvertView type0");
convertView = mInflater.inflate(R.layout.listitem_highscore_pager, null);
convertView.setTag(R.layout.listitem_highscore_pager, holder2);
break;
}
}
} else{
// Get the ViewHolder back to get fast access to the TextViews
holder = (ViewHolder) convertView.getTag(R.layout.baseadapter);
holder2 = (ViewHolder2)convertView.getTag(R.layout.baseadapter1);
}
switch(type){
case TYPE_SCORE:
holder.holderText.setText("type1");
break;
case TYPE_PAGER:
holder2.holder2Text.setText("type2");
break;
}
}
查看持有人:
static class ViewHolder {
//Place your views here for example:
TextView holderText;
}
static class ViewHolder2{
TextView holder2Text;
}
答案 1 :(得分:1)
getItemViewType()
必须返回稳定值。 IOW,对于position
0
,getItemViewType()
必须始终返回TYPE_PAGER
,而不是基于其他mHasBefore
值。< / p>
如果您希望值不稳定,则每次需要更改值时都需要调用notifyDataSetChanged()
。 IOW,如果您从最初的任何内容切换mHasBefore
,则需要致电notifyDataSetChanged()
,如果您将mHasBefore
更改回其原始值,则需要再次调用。
答案 2 :(得分:-2)
如何在ListView上使用HeaderView和FooterView?
那样,你不必处理多种类型......