2012-07-25 41 views
2

我正在關注一個偉大的編碼示例:This SO question。它關於實現一個到數組適配器的SectionIndexer接口。SectionIndexer - 與ArrayAdapter和CustomObject一起使用?

但是,如果您的ArrayAdapter傳遞ArrayList < MyObject>不是ArrayList < String>,那麼您將如何執行相同的操作?

例如,這是我的代碼與他的代碼不同的地方。他有:

class AlphabeticalAdapter extends ArrayAdapter<String> implements SectionIndexer { 
private HashMap<String, Integer> alphaIndexer; 
private String[] sections; 

public AlphabeticalAdapter(Context c, int resource, List<String> data) { 

    alphaIndexer = new HashMap<String, Integer>(); 
    for (int i = 0; i < data.size(); i++) { 
     String s = data.get(i).substring(0, 1).toUpperCase(); 
     alphaIndexer.put(s, i); 
    } 

    // other stuff 

} 

我有問題適應循環到我的情況。我無法像他那樣衡量尺寸。在哪裏他有以上,我的適配器開始。

public class CustomAdapter extends ArrayAdapter<Items> implements 
    SectionIndexer { 

    public ItemAdapter(Context context, Items[] objects) { 

在那裏他路過一個ArrayList中,我有三通過,但要做到這一點,必須在自定義對象類來包裝。我想排序的ArrayLists之一是名爲「name」的類中的三個字段之一。這顯然是一個字符串。

我想根據名稱字段按字母順序滾動查看SectionIndex。如何更改來自其他問題的示例代碼以在這種情況下工作?

他在哪裏有「data.size()」,我需要像「name.size()」 - 我想?

回答

2

在他傳遞一個ArrayList的地方,我必須傳入三個,但是要做到這一點,必須包裝在一個自定義對象類中。我想排序的 ArrayList中的一個是名爲「name」的類 中的三個字段之一。

你不用有三個ArrayLists,有自定義對象的ArrayList從三個ArrayLists分別建立了(所以尺碼是你傳遞給適配器的List的大小)。從這個角度來看在代碼中唯一的變化是使用從自定義對象Items建部:

for (int i = 0; i < data.size(); i++) { 
    String s = data.get(i).name.substring(0, 1).toUpperCase(); 
    if (!alphaIndexer.containsKey(s)) { 
     alphaIndexer.put(s, i); 
    } 
} 
// ... 

還有沒有其他變化。您可能還需要使用排序Items您傳遞給適配器的List

Collections.sort(mData); 

在您Items類必須實現Comparable<Items>接口:

class Items implements Comparable<Items> { 
     String name; 
     // ... rest of the code 

     @Override 
     public int compareTo(Items another) { 
      // I assume that you want to sort the data after the name field of the Items class 
      return name.compareToIgnoreCase(another.name); 
     } 

    } 
+0

嘿感謝!我編輯了我的代碼,顯示了我應該包含的其他部分。我添加了我的Adapter的構造函數。我實際上傳遞了一個Array對象,而不是ArrayLists,我相信它會再次改變for循環? – KickingLettuce 2012-07-25 14:36:25

+1

@KickingLettuce唯一的變化是獲取數據大小的語法,而不是'data.size()'你會使用'data.length',因爲你使用了一個數組。 – Luksprog 2012-07-25 15:06:51

+0

再次感謝。我通過Eclipse的幫助確定了這一點。然而,它沒有給我這樣的建議:'data.get(i).name.substring(0,1)'這是我得到的唯一的錯誤。我想它會是數據[我] .name.substring(0,1),但我認爲它也有問題。 – KickingLettuce 2012-07-25 16:23:27

相關問題