嗨,我发现了一个非常奇怪的问题,我无法理解..希望有人可以帮助我:
如果所有 View 都显示在屏幕上,我的列表看起来会很棒。一旦屏幕变小(或列表变长),有时条目的 View 就会与应有的不同。可以通过向上或向下滚动以使条目移出窗口来限制此问题。
我有一个 ListView ,其中包含不同的条目类型,并且具有不同的布局文件。这是应该决定显示什么布局的方法:
public View getView(int position, View view, ViewGroup parent) {
NavigationListEntry i = entries.get(position);
View v = view;
if (v == null)
switch(i.Type) {
case ACTIVE_ENTRY:
v = inflater.inflate(R.layout.list_nav_row_active, null);
break;
case HEADER:
v = inflater.inflate(R.layout.list_nav_row_header, null);
break;
...
default:
v = inflater.inflate(R.layout.list_nav_row_active, null);
break;
}
}
您知道为什么会发生这种情况吗?
/编辑 如果我只是删除“if (v == null)”,它似乎可以工作
最佳答案
如果删除if(v==null)
,您就不会重用已经膨胀的 View 。如果这样做, ListView 将会有点迟缓。
最好的办法是
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
NavigationListEntry i = getItem(position);
if(null == convertView){
convertView = inflateNewView(i.type);
holder = (ViewHolder) convertView.getTag();
} else{
//getting tag to obtain the already found views
holder = (ViewHolder) convertView.getTag();
if(holder.type != i.type){
convertView = inflateNewView(i.type);
holder = (ViewHolder) convertView.getTag();
}
}
//always update the elements
holder.title.setText(i.getTitle());
holder.desc.setText(i.getDesc());
holder.content.setText(i.getContent());
return convertView;
}
/**
* Inflates a new view for the specified type
* @return the newly inflated view
*/
private View inflateNewView(int type){
View convertView = null;
switch(type) {
case ACTIVE_ENTRY:
convertView = inflater.inflate(R.layout.list_nav_row_active, null);
break;
case HEADER:
convertView = inflater.inflate(R.layout.list_nav_row_header, null);
break;
...
default:
convertView = inflater.inflate(R.layout.list_nav_row_active, null);
break;
}
holder = new ViewHolder();
convertView = inflater.inflate(LAYOUT_RESOURCE, null);
holder.title = (TextView) convertView.findViewById(R.id.txtTitle);
holder.desc = (TextView) convertView.findViewById(R.id.txtDesc);
holder.content = (TextView) convertView.findViewById(R.id.txtContent);
holder.type = type;
//setting tag to reduce hierarchy lookup
convertView.setTag(holder);
return convertView;
}
/**
* Holder class to improve performance. Helps in reducing view hierarchy lookup
*/
private static class ViewHolder {
TextView title;
TextView desc;
TextView content;
int type;
}
这是最好的方法,至少会尝试回收您的 View 。 希望这有帮助
关于java - ListView 条目在滚动时会更改其布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13605206/