2016-04-05 36 views
0

我按照給予鏈接: Android ListView adapter with two ArrayLists如何使用兩個不同大小的動態ArrayList在android中創建listview?

但在上述鏈路解決方案既數組列表添加到一個ArrayList中。可以請建議任何答案,因爲我的要求如下:

要求:我從服務器獲取數據都是不同的API,所以如何設置爲解析後的列表視圖?

請提出任何解決方案提前 感謝

+0

我假設你的東東d將不同的項目放入列表中。對?您可以創建一個額外的類,並只使用這兩個需要使用的字段。另外,還有許多其他方法可以實現同樣的目標。 –

+0

是的,你可以請分享任何鏈接 –

回答

1

有一些事情你可以在這種情況下,這樣做:

  1. 你的數據模型中繼承(或接口)模式,讓抽象的數據爲統一的類型並在使用時顯示它getItemViewType確實區分數據

  2. 使用第三方庫如mergelist並使用2個不同的適配器

1

當你的模型對兩者都不相同時,你可以創建一個名爲CustomInterface的接口並將它實現到你的兩個模型中。然後在適配器,而不是模型,使用CustomInterface並在getView,你必須檢查當前的模型,如:

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
LayoutInflater theInflater = LayoutInflater.from(getContext()); 
View theView = theInflater.inflate(R.layout.custom_row, parent, false); 
if(entity instanceof Obj1){ 
    // Model 1 
} else if(entity instanceof Obj2){ 
    // Model 2 
} 
return theView; 
} 

記住,列表僅適用於同類集合。如果您有異構集合,則可以在所有模型上實現接口並創建接口列表,然後可以在該列表中放置實現相同接口的任何模型。

+0

謝謝亞西爾先生,現在我明白了。 –

+0

如果這解決了您的問題,請將其標記爲正確答案 –

1

樣品在這裏。

  1. 接口

    public interface DataType { 
         String getTitle(); 
         String getAddress(); 
    } 
    
  2. 數據類

    public class AData implements DataType { 
        String titleA; 
        String addressA; 
    
        @Override 
        public String getTitle() { 
         return titleA; 
        } 
    
        @Override 
        public String getAddress() { 
         return addressA; 
        } 
    
        // getter & setter 
    } 
    
    public class BData implements DataType { 
        String titleB; 
        String addressB; 
    
        @Override 
        public String getTitle() { 
         return titleB; 
        } 
    
        @Override 
        public String getAddress() { 
         return addressB; 
        } 
    
        // getter & setter 
    } 
    
  3. 適配器

    public class CustomAdapter implements BaseAdapter { 
    
    List<DataType> arrayList; 
    
    // getCount... 
    
    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
        // inflating views, bindings, reuse, etc 
    
        DataType data = arrayList.get(position); 
        textView.setText(data.getTitle()); 
        textView.setText(data.getAddress()); 
    
        // return ... 
    
    } 
    
相關問題