Friday, January 16, 2015

How to use ArrayAdapter with ListView in Android

ListView ArrayAdapter
activity_main.xml

<ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
</ListView>
MainActivity.java code snippet

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 //initializing a String array
 String[] array = new String[]{"one","two","three","four","five","six","seven"};
 //initializing an ArrayList from array
 List<String> list = new ArrayList<String>(Arrays.asList(array));

 //refer ListView from xml layout file
 ListView lv = (ListView) findViewById(R.id.list_view);
 //data bind ListView with ArrayAdapter
 lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list));
}
Imported Class

import android.widget.ArrayAdapter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.widget.ListView;
More android examples