2014-09-04 102 views
-3

請告訴我如何在listview arrayadapter中添加項目? 我只發現瞭如何使標準的適配器在listview arrayadapter中添加項目

活動:

public class Activity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.m); 

     ListView lv=(ListView) findViewById(R.id.lv); 
     String[] Id1={"1","2","3"}, Text1={"one","two","three"}; 

     CustomAdapter ad = new CustomAdapter(this, Id1 , Text1); 
     ad.setCustomListener(new LVListener() { 
      public void onClick(String text) { 
       Log.d("APP", text); 
      } 
     }); 
     lv.setAdapter(ad); 

     Button btn = (Button) findViewById(R.id.btn); 
     btn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       btn.setVisibility(View.GONE); 
       String[] Id2={"4","5","6"},Text2={"four","five","six"}; 
       // add Id2 and Text2 in listview 
      } 
     }); 
    } 
} 

CustomAdapter:

public class CustomAdapter extends ArrayAdapter<String> { 
    private final Context context; 
    private final String[] id, text; 
    private ListViewListener micl; 
    public CustomAdapter(Context context, String[] id, String[] text) { 
     super(context, R.layout.list, id); 
     this.context = context; 
     this.id = id; 
     this.text = text; 
    } 

    public void setCustomListener(ListViewListener micl) { this.micl = micl; } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View View = inflater.inflate(R.layout.list, parent, false); 

     final int pos = position; 
     final TextView tView = (TextView) View.findViewById(R.id.textView); 
     tView.setText(text[pos]); 

     rowView.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
       if (micl != null) 
        micl.onClick(text[pos]); 
      } 
     }); 
     return View; 
    } 
} 

我試着用notifyDatasetChanged做的(),但什麼都沒有發生。 請告訴我該怎麼做。

回答

1

ArrayAdapteradd方法,但爲了使用它,你提供給super的數據集不能是一個數組,這是因爲使用Arrays.asList(objects),它返回一個不可變列表。從文檔

返回指定數組中的對象列表。 列表的大小不能修改,即不支持添加和刪除,但可以設置元素。設置元素會修改底層 陣列。