2011-07-14 28 views
0

我目前正在建立一個ListView非常類似於今天任何Android手機隨附的標準鬧鐘應用程序。在應用程序中,他們有一個ListView,每個行都有不同的視圖。有一個自定義ListView與不同的選項可供選擇

例如:

http://www.androidpeople.com/wp-content/uploads/2010/05/listviewwithmultiplechoice.png

http://www.talkandroid.com/android-forums/attachments/android-development-answers-tutorials-code-snippets/360d1234754310-add-edittext-backgroundtxt-child-expandable-list-screencap1.png

我想對於這兩個選項使用複選框和可擴展的查看同ListView控件。我試過尋找教程,但沒有真正幫助過。

在我的代碼中,我期待這個視圖是可擴展列表視圖和多選視圖的組合。 做這種事情的最好方法是什麼? 這是我目前的代碼。

public class AlarmList extends ListActivity { 
    AlarmListItem[] items = { 
      new AlarmListItem("Turn On Alarm", Alerts.class), 
      new AlarmListItem("Time", Person.class), 
      new AlarmListItem("Time", MTSU_Android.class), 
      new AlarmListItem("Sound", Person.class), 
      new AlarmListItem("Vibrate", Alerts.class), 
      new AlarmListItem("Repeat", Alerts.class), 
      new AlarmListItem("Volume", MTSU_Android.class), 
      new AlarmListItem("BackupAlarm", Person.class)}; 

      @Override 
      public void onCreate (Bundle icicle) 
      { 
       super.onCreate(icicle); 
       setContentView(R.layout.main3); 
       //ListView list1 = ((ListView)findViewById(R.id.ListView01)); 
       setListAdapter(new ArrayAdapter<AlarmListItem>(
         this, android.R.layout.simple_list_item_1, items)); 
      } 

      @Override 
      protected void onListItemClick(ListView l, View v, int position, long id) 
      { 
       super.onListItemClick(l, v, position, id); 
       final Intent intent = new Intent(this, items[position].getActivity()); 
       startActivityForResult(intent, position); 
      } 

回答

0

您需要擴展ListAdapter並覆蓋getView。使用getItem使用傳遞的位置來獲取對象,然後返回適合傳遞的對象的視圖。

如果視圖依賴於對象的類,則使用instanceof進行測試。

+0

所以你說,而不是ListActivity我需要擴展ListAdapter? 然後,一旦我用getitem獲得對象,是否需要爲每個視圖創建幾個新的xml文件?如:temp1.xml,temp2.​​xml,temp3.xml, 然後將它們中的每一個充氣到不同的視圖?像... 'getItem(position); layoutInflater myInflater; 查看v = myInflater.inflate(R.layout.temp1); View v1 = myInflater.inflate(R.layout.temp2);' 那麼......? – cj1098

+0

保持你的ListActivity,但是創建一個自定義ListAdapter(例如,擴展ArrayAdapter 。通過調用setListAdapter(yourCustomListAdapter)來使用它 是的,每次調用getView時都要膨脹一個不同的視圖確保傳入的視圖不爲null而且在你膨脹新的一切之前,你不希望膨脹的類型 - 爲了效率。 – Gallal