2014-01-18 134 views
1

我想動態地添加信息到ListView。我添加的信息包括「設備名稱」(主要項目)和「MAC地址」(子項目)。下面是一個來自在線的例子。注意:我想用設備1的名稱替換項目1,用設備1的MAC地址替換子項目1,等等。這必須動態完成,因爲在掃描設備時列表正在填充。在Android中動態添加子項目ListView

Valid XHTML

在此之前被標記爲重複,我已經看過了下面的問題,他們並沒有幫助我:Adding ListView Sub Item Text in AndroidHow to add subitems in a ListViewAdding Items and Subitems to a ListView

結論我來通過閱讀這些問題是我需要實施自定義ArrayAdapter並覆蓋getView()方法。我創建了一個自定義佈局在這兩個文本的意見:

cyan_list.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

<TextView 
    android:id="@+id/main_item" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:textColor="@color/cyan"/> 

<TextView 
    android:id="@+id/sub_item" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:textColor="@color/dark_cyan"/> 

</LinearLayout> 

然後我嘗試創建我的活動類的定製ArrayAdapter,但我失去至於什麼把我的public View getView(final int position, View convertView, ViewGroup parent)方法。此外,正在創建一個自定義的ArrayAdapter,如果我所要做的只是添加一個textview子項目?

+0

您是否發現解決方案可以請您上傳相同的代碼,如果可能的話,沒有壓力:) –

回答

2

答案您的問題是:沒有,你不需要創建一個自定義ArrayAdapter如果你只是想添加項目。然而,如果您的佈局是自定義的,我建議您創建它,因爲您可以很好地控制所顯示的項目。您沒有在創建ArrayAdapter的地方添加代碼,但在您的情況下,我會使用this的構造函數。重要的部分是第三個參數:在您的活動中,您應該將ArrayList與您添加到ArrayAdapter的初始項目一起存儲,然後,如果您想添加新項目,只需將其添加到ArrayAdapter並撥打notifyDataSetChanged()在你的適配器上。只需做到這一點,您的項目將被添加到佈局並顯示。如果您需要替代您自己的ArrayAdapter覆蓋GetView方法,我推薦這個link,它幫助我理解整個事情。

+0

謝謝你的幫助反應! –

+0

很高興爲您提供幫助,一旦您最終選擇了最能幫助您的答案,請不要忘記接受它,這樣其他用戶也可以知道最能幫助您的是什麼。 – nKn

1

,您在搜索一些的ListView例如,在谷歌喜歡這些教程:

http://www.vogella.com/tutorials/AndroidListView/article.html

http://www.mkyong.com/android/android-listview-example/

我覺得他們一步解釋一步如何創建一個列表適配器

+0

那麼除了自定義適配器,還有沒有辦法添加子項?這看起來很奇怪,因爲在eclipse預覽中你可以看到「subitem」,所以我認爲會有一個不需要構建一個自定義適配器的方式來添加一個:( –

1

您需要添加getter方法到您的適配器

YourAdapter ...{ 

List<Device> items = new ArrayList<Device>; 

public List<Device> getItems(){ 
return items; 
} 

} 

然後更改項目,你需要

...{ 
//for 1s item 
Device item = getItems().get(0); 
item.setTitle(macAdress) 

} 

,並呼籲notifyDataSetChanged您的適配器

... 
yourListView.getAdapter().notifyDataSetChanged(); 
} 

完蛋了。現在您可以更改您的清單數據。

對於你的問題,我想是的。最好是創建自己的適配器,以便稍後執行它的簡單可能性。在你的情況下(如果你不想在每個標題改變後改變你的適配器),你需要自定義一個。歡呼聲