2012-02-14 75 views
0

返回資源陣列我定義爲一個ListView如下:如何從一個ListView

<ListView 
android:key="key1" 
android:title="@string/title" 
android:summary="@string/summary" 
android:entries="@array/options" 
android:entryValues="@array/values" /> 

條目&值在XML文件中指定的,你可以看到。我如何以編程方式從ListView中獲取條目數組?

沿着這個東西線:

ListView myListView = this.findViewById(R.layout.my_layout); 
String[] myListViewEntries = context.getResources().getStringArray(myListView.???????); 

任何幫助,將不勝感激。

請不要告訴我硬編碼一個數組名(例如「R.array.some_array」),這必須使用ListView對象完成,而不是數組名的硬編碼。

感謝

回答

1

我想你可以通過調用myListView.getAdapter()應返回用於創建列表條目適配器實現這一目標。屆時您可以添加/編輯/刪除適配器中的項目以進一步修改您的列表。

這是怎麼了,你可以從適配器檢索您的字符串數組:

String[] array = getStringArray(myListView.getAdapter()); 

和您的靜態方法:

public static String[] getStringArray(ListAdapter adapter){ 
     String[] a = new String[adapter.getCount()]; 

     for(int i=0; i<a.length; i++) 
      a[i] = adapter.getItem(i).toString(); 

     return a; 
    } 
+0

你可以調用什麼方法來形成適配器來返回數組? – 2012-02-14 20:28:53

+0

我看到它有一個'getItem(int i)'方法。有沒有方法返回一個數組,或者我必須循環並從所有項目手動創建數組? – 2012-02-14 20:30:45

+0

是的,你需要遍歷所有項目來創建你自己的數組。但仍然比硬編碼更好,不是嗎? :) – waqaslam 2012-02-14 20:36:38

0

你可以得到所有從適配器的元素

ListAdapter adapter = ListView.getAdapter() 

然後你可以遍歷所有元素

for(int i = 0; i < adapter.getCount(); i++) { 
    doSomethingWithElement(adapter.getItem(i)); 
} 
相關問題