我以這種方式解決了這個問題。希望對你有幫助。首先,你必須爲不同類型創建模型。你應該爲不同的模型創建自定義佈局。 例如,我有兩個類型: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"
}