I am trying to dynamically add information to a ListView. The information I am adding consists of a "Device Name" (the main item) and "MAC Address" (the sub item). An example from online is below. Note: I want to replace Item 1 with a device 1's name, sub item 1 with device 1's MAC address, and so on. This MUST be done dynamically because the list is being populated as devices are scanned for.
.
Before this is marked as a repeat, I have looked at the following questions and they have not helped me: Adding ListView Sub Item Text in Android, How to add subitems in a ListView, Adding Items and Subitems to a ListView
The conclusion I have come to through reading these questions is that I need to implement a custom ArrayAdapter
and override the getView()
method. I have created a custom layout with two text views in it:
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>
I then try to create a custom ArrayAdapter in my Activity class, but I am lost as to what to put in my public View getView(final int position, View convertView, ViewGroup parent)
method. Additionally, is creating a custom ArrayAdapter necessary if all I am trying to do is add a textview sub item?
The answer to your question is: NO, you don't need to create a custom ArrayAdapter
if you just want to add items. I recommend, however, creating it if your layout is customized, as you'll gain so much control over the items you're displaying. You didn't add your code where you create your ArrayAdapter
, but in your case I'd use this constructor. The important part is the third parameter: In your activity, you should store an ArrayList
with the initial items you're adding to your ArrayAdapter, then, if you want to add a new item, you simply add it to the ArrayAdapter
and call notifyDataSetChanged()
on your adapter. Simply doing that, your item will be added to the layout and displayed. If you need to override the GetView
method for your own ArrayAdapter
, I recommend this link, it helped me understanding the whole thing.