2015-02-06 40 views
0

我的問題是關於listviews。比方說,我的ListView我將有3種不同的物品,隱藏/顯示ListItem組件vs不同的listitem視圖

1 - 與封面圖片 3-列表項沒有圖像 2 - 列表項與2次到位封面圖像的圖像平方列表項

可以說,我能結構列表項這樣

<LinearLayout> 
    <ImageView visibility gone /><ImageView with visibility gone/> 
</LinearLayout> 

所以,當我寫我的適配器此列表視圖,是它使用不同的佈局,這些或以上使用類似和隱藏/顯示imageviews更方便取決於圖像數量。有沒有更好的?謝謝

回答

0

我會覆蓋getViewTypeCount()getItemViewType(int position),並基於它在我的getView()我會隱藏/顯示ImageViews。您的3種類型的項目沒有顯着差異,隱藏/顯示可以輕鬆實現最終結果。同樣,當你使用getItemViewType(int position)時,Android仍然會重複使用你列表中的很多視圖。

0

我以這種方式解決了這個問題。希望對你有幫助。首先,你必須爲不同類型創建模型。你應該爲不同的模型創建自定義佈局。 例如,我有兩個類型:OneObject和TwoObject

public class MainObject { String type; 
    public MainObject(String t){ this.type = t;} 
} 

public class OneObject extends MainObject { String image; 
    public OneObject(String t, String image){ 
     super(t); 
     this.image = image; 
    } 
} 

public class TwoObject extends MainObject { String place; 
     public TwoObject(String t, String p) { 
     super(t); 
     this.place = p; 
    } 
} 

然後。當你添加數據到arraylist,你可以像這樣添加。

ArrayList<MainObject> objlist = new ArrayList<>(); 

     objlist.add(new MainObject("main")); 
     objlist.add(new OneObject("one", "image")); 
     objlist.add(new TwoObject("two","place")); 

在適配器中,您將獲得該ArrayList.And,然後您可以檢查應該投射哪個模型以及應該使用哪種佈局。例如...

ArrayList<MainObject> objlist = new ArrayList<>(); 


    //IN ADAPTER 

    .............. 

      MainObject obj = objlist.get(position); 

      //u can check in other way 

      //if(obj.type.equals("one")) 
      if(obj instanceof OneObject){ 
       //this object is "OneObject" 
      } 
      //else if(obj.type.equals("two")) 
      else if(obj instanceof TwoObject){ 
       //this object is "TwoObject" 
      } 
      //else if(obj.type.equals("main")) 
      else if(obj instanceof MainObject){ 
       //this object is "MainObject" 
      }