Wednesday, May 13, 2015

Android ListView with Adapter

                                 Android ListView with Adapter

In Android development, any time we want to show a vertical list of scrollable items we will use a ListView which has data populated using an Adapter. The simplest adapter to use is called an ArrayAdapter because the adapter converts an ArrayList of objects into View items loaded into the ListView container.
ListView with Adapter conceptual Diagram.
The ArrayAdapter fits in between an ArrayList (data source) and the ListView (visual representation) and configures two aspects:
  • Which array to use as the data source for the list
  • How to convert any given item in the array into a corresponding View object.

 Using a Basic ArrayAdapter

To use a basic ArrayAdapter, you just need to initialize the adapter and attach the adapter to the ListView. First, we initialize the adapter:

ArrayAdapter<String> itemsAdapter = 
    new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
 
The ArrayAdapter requires a declaration of the type of the item to be converted to a View (a String in this case) and then accepts three arguments: context (activity instance), XML item layout, and the array of data. Note that we've chosen simple_list_item_1.xml which is a simple TextView as the layout for each of the items.

Now, we just need to connect this adapter to a ListView to be populated:

ListView lv= (ListView) findViewById(R.id.listview1);
lv.setAdapter(itemsAdapter);
 

Example:

activity_main.xml

 <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ListView>

 

MainActivity.java

public class MainActivity extends ActionBarActivity {
ListView lv;
String[] data = new String[]{"Nokia","Samsung","LG","Micromax","iPhone","Nexus s","Karbone","Lava","Geonie"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView)findViewById(R.id.listview1);
        ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,data);
        lv.setAdapter(itemsAdapter);
       
    }
 

Happy coding :)


No comments:

Post a Comment