2014-08-30 90 views
0

我有一个列表视图,并在其适配器根据一些情况我充气布局。例如考虑这个:ListView显示错误的布局

if (state1){ 
    resource = R.layout.layout_1 

}else if (state2){ 
    resource = R.layout.layout_2 
} 
if (convertedView == null) { 
    view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 
       .inflate(resource, parent,false); 
}    
return view; 

但有时ListView会感到困惑,它显示不同的状态相同的布局。我相信代码中没有错。但在ListView行为。任何建议? 谢谢

+0

你怎样的状态?每行或每个Listview是状态吗? – hoomi 2014-08-30 07:40:02

+0

我根据新增加的数据得到状态:)但这不是问题。请看我自己的回答:) – user2808671 2014-08-30 07:49:54

+0

[你知道'ListView'使用回收机制吗?](http://stackoverflow.com/a/14108676/1841194) – 2014-08-30 10:01:58

回答

0
if (state1){ 
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 
       .inflate(R.layout.layout_1, parent,false); 

}else if (state2){ 
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 
       .inflate(R.layout.layout_2, parent,false); 
} 




return view; 
+0

谢谢,但这与我写的相同。我找到了解决办法并将其写下来。 – user2808671 2014-08-30 07:43:54

0

那么我找到了解决方案。

问题是我检查ConverView参数是否为空,那么适配器不会膨胀新视图并且它使用最后一个。如果我删除这个条件并且让适配器始终膨胀一个新的布局,问题就解决了。

像这样:

public View getView(int position, View convertedView, ViewGroup parent) { 
View view; 
int resource = 0; 
if (state1){ 
    resource = R.layout.layout_1; 
}else{ 
    resource = R.layout.layout_2; 

} 
//if (convertedView == null) { //I should Delete this condition 
    view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 
      .inflate(R.layout.layout_2, parent,false); 
//} 
return view;