2011-02-26 64 views
17

ArrayAdapter.add()方法不適用於我。我使用Eclipse Helios 3.6和ADT插件,Target Source是Froyo 2.2仿真器和2.2 HTC Evo 4g。這是我的java類Android ArrayAdapter.Add方法不起作用

import android.app.Activity; 
    import android.os.Bundle; 
    import android.widget.ArrayAdapter; 

    public class Main extends Activity { 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 

      String[] entries = {"List Item A", "List Item B"}; 

      ArrayAdapter<String> arrAdapt=new ArrayAdapter<String>(this, R.layout.list_item, entries); 

      arrAdapt.setNotifyOnChange(true); 
      arrAdapt.add("List Item C"); 
     } 
    } 

,這裏是我的佈局列表項(list_item.xml)

<?xml version="1.0" encoding="utf-8"?> 
<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    android:padding="10dp" 
    android:textSize="12sp" 
</TextView> 

這是給我和錯誤,說

的logcat的引起者: java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:411) at java.util.AbstractList.add(AbstractList.java:432) 在 android.widget.ArrayAdapter.add(ArrayAdapter.java:178)

回答

38

我剛學的,但如果我在看source正確,ArrayAdapter的構造函數不會複製對數組或列表中每個元素的引用。相反,它直接使用傳入的列表,或者對於數組使用asList()將原始數組視爲列表。由於asList()返回的列表仍然只是底層數組的表示,所以無法對數組做任何事情(如調整大小)。

嘗試傳遞一個像ArrayList而不是數組的列表。

ArrayList<String> entries = 
     new ArrayList<String>(Arrays.asList("List Item A", "List Item B")); 

ArrayAdapter<String> arrAdapt= 
     new ArrayAdapter<String>(this, R.layout.list_item, entries); 

arrAdapt.setNotifyOnChange(true); 
arrAdapt.add("List Item C"); 
+3

如果這是正確的,那麼ArrayAdapter文檔可能會更清晰。沒有提及根據使用的構造函數添加元素的能力。 – erichamion 2011-02-26 14:40:57

+0

你是對的,這解決了我的問題,我的列表視圖LinearLayout現在可以工作! – Mike 2011-02-26 17:28:42