2014-08-30 89 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;