android.widget.ListView is widely used in android mobile app. It displays all the list items in the form of a vertical list. This article will show you examples about how to create ListView and how to add item data in it.
1. How To Get A ListView Object.
There are two ways to create a ListView.
- Use android.widget.ListView widget directly.
- Make your activity class extends android.app.ListActivity. Then you can call it’s setAdapter() method to set item data, and it’s onListItemClick() method is used to response list item click action.
After you get the ListView object, you need to add item data in it through Adapter. There are following Adapters that you can use.
- ArrayAdapter.
- SimpleAdapter.
- BaseAdapter.
You can even use other adapters, but these three adapters are most used. We will show you above adapter examples later.
2. ListView Properties And Methods.
- android:choiceMode : The value can be singleChoice (can only select one item ), multipleChoice( can select multiple item ) or none.
- android:divider : It is a color or drawable object id, used to set divider color.
- android:dividerHeight : Set the divider height.
- android:entries : The value is a array resource id defined in android studio. The array data will be shown in the ListView.
- android:headerDividersEnabled : Boolean value, true means draw divider after header view.
- android:footerDividersEnabled : Boolean value, true means draw divider before footer view.
- setOnItemClickListener() : Set OnItemClickListener object which will response to ListView item click event.
3. ListView ArrayAdapter Example.
If you can not watch the above video, you can see it on the youtube URL https://youtu.be/c5Fv78xCI6M
activity_list_view.xml
<ListView android:id="@+id/listViewExample" android:layout_width="match_parent" android:layout_height="wrap_content" android:divider="@android:color/holo_green_light" android:dividerHeight="5dp" android:clickable="true" android:choiceMode="singleChoice" />
ListViewActivity.java
Please note the second parameter for ArrayAdapter constructor can have below values.
- simple_list_item_1 : Each list item is a TextView object.
- simple_list_item_2 : Each list item is a TextView object, text size is bigger.
- simple_list_item_checked : Each list item is a checked checkbox.
- simple_list_item_single_choice : Display a radio button in the right of each list item. Even it is a radio button, it can be multiple checked if ListView’s android:choiceMode value is multipleChoice.
- simple_list_item_multiple_choice : Display a checkbox in the right of each list item. Even it is a checkbox, it can be single checked if ListView’s android:choiceMode value is singleChoice.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, dataList);
package com.dev2qa.example; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class ListViewActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); this.arrayAdapterListView(); } // This method use an ArrayAdapter to add data in ListView. private void arrayAdapterListView() { setTitle("dev2qa.com - ArrayAdapter List View Example"); List<String> dataList = new ArrayList<String>(); dataList.add("Java"); dataList.add("Android"); dataList.add("JavaEE"); dataList.add("JSP"); dataList.add("JDBC"); ListView listView = (ListView)findViewById(R.id.listViewExample); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, dataList); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) { Object clickItemObj = adapterView.getAdapter().getItem(index); Toast.makeText(ListViewActivity.this, "You clicked " + clickItemObj.toString(), Toast.LENGTH_SHORT).show(); } }); } }
4. ListView SimpleAdapter Example.
If you can not watch the above video, you can see it on the youtube URL https://youtu.be/9BYH4Ftclv0
activity_list_view.xml
<ListView android:id="@+id/listViewExample" android:layout_width="match_parent" android:layout_height="wrap_content" android:divider="@android:color/holo_green_light" android:dividerHeight="5dp" android:clickable="true" android:choiceMode="singleChoice" />
ListViewActivity.java
Please note the SimpleAdapter creation code. There are 5 parameters in the SimpleAdapter constructor.
- First parameter : This is the context object that this SimpleAdapter will be used with.
- Second parameter : This is a List<Map<String, Object>> object, each map object in the list represent a ListView item data.
- Third parameter : This is the ListView’s item UI component layout xml. It decides which UI components will be shown in each ListView item.
- Fourth parameter : This String array contains map object’s keys. Each key related map value will be shown in the ListView item.
- Fifth parameter : This int array contains the view object’s resource id in item layout xml file(second parameter specified). Each view object will display related value extracted from map object use keys( fourth parameter specified) by order.
SimpleAdapter simpleAdapter = new SimpleAdapter(this,itemDataList,android.R.layout.simple_list_item_2, new String[]{"title","description"},new int[]{android.R.id.text1,android.R.id.text2});
package com.dev2qa.example; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class ListViewActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); this.simpleAdapterListView(); } // This method use SimpleAdapter to show data in ListView. private void simpleAdapterListView() { setTitle("dev2qa.com - SimpleAdapter List View Example"); String[] titleArr = { "Name", "Sex", "Age", "Location","Email"}; String[] descArr = { "Jerry", "Male", "43", "Singapore", "webmaster@dev2qa.com" }; ArrayList<Map<String,Object>> itemDataList = new ArrayList<Map<String,Object>>();; int titleLen = titleArr.length; for(int i =0; i < titleLen; i++) { Map<String,Object> listItemMap = new HashMap<String,Object>(); listItemMap.put("title", titleArr[i]); listItemMap.put("description", descArr[i]); itemDataList.add(listItemMap); } SimpleAdapter simpleAdapter = new SimpleAdapter(this,itemDataList,android.R.layout.simple_list_item_2, new String[]{"title","description"},new int[]{android.R.id.text1,android.R.id.text2}); ListView listView = (ListView)findViewById(R.id.listViewExample); listView.setAdapter(simpleAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) { Object clickItemObj = adapterView.getAdapter().getItem(index); Toast.makeText(ListViewActivity.this, "You clicked " + clickItemObj.toString(), Toast.LENGTH_SHORT).show(); } }); } }
5. ListView Custom SimpleAdapter Example.
This example will customize a SimpleAdapter object which use self defined ListView item layout to add a picture at the beginning of each ListView item.
If you can not watch the above video, you can see it on the youtube URL https://youtu.be/XJOX6qtZuxk
activity_list_view.xml
<ListView android:id="@+id/listViewExample" android:layout_width="match_parent" android:layout_height="wrap_content" android:divider="@android:color/holo_green_light" android:dividerHeight="5dp" android:clickable="true" android:choiceMode="singleChoice" /> <!-- Below layout xml is used for each ListView's item.--> <RelativeLayout android:id="@+id/userListItem" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/userImage" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentTop="true" android:layout_alignParentBottom="true"/> <TextView android:id="@+id/userTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp" android:textStyle="bold" android:layout_alignParentTop="true" android:layout_toRightOf="@id/userImage"/> <TextView android:id="@+id/userDesc" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp" android:textStyle="bold" android:layout_alignParentBottom="true" android:layout_toRightOf="@id/userImage"/> </RelativeLayout>
ListViewActivity.java
package com.dev2qa.example; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static com.dev2qa.example.R.id.userDesc; import static com.dev2qa.example.R.id.userTitle; public class ListViewActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); this.customSimpleAdapterListView(); } // This method shows how to customize SimpleAdapter to show image and text in ListView. private void customSimpleAdapterListView() { setTitle("dev2qa.com - Custom SimpleAdapter List View Example"); String[] titleArr = { "Name", "Sex", "Age", "Location","Email"}; String[] descArr = { "Jerry", "Male", "43", "Singapore", "webmaster@dev2qa.com" }; ArrayList<Map<String,Object>> itemDataList = new ArrayList<Map<String,Object>>();; int titleLen = titleArr.length; for(int i =0; i < titleLen; i++) { Map<String,Object> listItemMap = new HashMap<String,Object>(); listItemMap.put("imageId", R.mipmap.ic_launcher); listItemMap.put("title", titleArr[i]); listItemMap.put("description", descArr[i]); itemDataList.add(listItemMap); } SimpleAdapter simpleAdapter = new SimpleAdapter(this,itemDataList,R.layout.activity_list_view, new String[]{"imageId","title","description"},new int[]{R.id.userImage, userTitle, userDesc}); ListView listView = (ListView)findViewById(R.id.listViewExample); listView.setAdapter(simpleAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) { Object clickItemObj = adapterView.getAdapter().getItem(index); HashMap clickItemMap = (HashMap)clickItemObj; String itemTitle = (String)clickItemMap.get("title"); String itemDescription = (String)clickItemMap.get("description"); Toast.makeText(ListViewActivity.this, "You select item is " + itemTitle + " , " + itemDescription, Toast.LENGTH_SHORT).show(); } }); }
6. ListView Custom BaseAdapter Example.
If you still need more customization for ListView item. You can use android.widget.BaseAdapter. Override it’s getCount() and getView() method.
This example set different item row background color and add a button for each item row.
If you can not watch the above video, you can see it on the youtube URL https://youtu.be/e71VJsnfRtw
activity_list_view_base_adapter.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/userListItem" android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/baseUserImage" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" /> <Button android:id="@+id/baseUserButton" android:layout_width="wrap_content" android:layout_height="match_parent" android:text="Click Me" android:layout_alignParentTop="true" android:layout_alignParentBottom="true" android:layout_toRightOf="@id/baseUserImage"/> <TextView android:id="@+id/baseUserTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp" android:textStyle="bold" android:layout_alignParentTop="true" android:layout_alignParentBottom="false" android:layout_toRightOf="@id/baseUserButton" /> <TextView android:id="@+id/baseUserDesc" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="20dp" android:textStyle="bold" android:layout_alignParentTop="false" android:layout_alignParentBottom="true" android:layout_toRightOf="@id/baseUserButton" /> </RelativeLayout>
ListViewActivity.java
package com.dev2qa.example; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class ListViewActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); this.customListViewViaBaseAdapter(); } // This method shows how to use BaseAdapter to customize ListView widget. private void customListViewViaBaseAdapter() { setTitle("dev2qa.com - Custom SimpleAdapter List View Example"); final String[] titleArr = { "Name", "Sex", "Age", "Location","Email"}; final String[] descArr = { "Jerry", "Male", "43", "Singapore", "webmaster@dev2qa.com" }; ArrayList<Map<String,Object>> itemDataList = new ArrayList<Map<String,Object>>();; int titleLen = titleArr.length; for(int i =0; i < titleLen; i++) { Map<String,Object> listItemMap = new HashMap<String,Object>(); listItemMap.put("imageId", R.mipmap.ic_launcher); listItemMap.put("title", titleArr[i]); listItemMap.put("description", descArr[i]); itemDataList.add(listItemMap); } // Create a BaseAdapter instance. BaseAdapter customBaseAdapter = new BaseAdapter() { // Return list view item count. @Override public int getCount() { return titleArr.length; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int itemIndex, View itemView, ViewGroup viewGroup) { if(itemView == null) { // First inflate the RelativeView object. itemView = LayoutInflater.from(ListViewActivity.this).inflate(R.layout.activity_list_view_base_adapter, null); } // Find related view object inside the itemView. ImageView imageView = (ImageView)itemView.findViewById(R.id.baseUserImage); TextView titleView = (TextView)itemView.findViewById(R.id.baseUserTitle); TextView descView = (TextView)itemView.findViewById(R.id.baseUserDesc); // Set background color by row number. int colorPos = itemIndex % 2; if(colorPos==0) { itemView.setBackgroundColor(Color.YELLOW); }else { itemView.setBackgroundColor(Color.GREEN); } // Set resources. imageView.setImageResource(R.mipmap.ic_launcher); final String title = titleArr[itemIndex]; final String desc = descArr[itemIndex]; titleView.setText(title); descView.setText(desc); // Find the button in list view row. Button itemButton = (Button)itemView.findViewById(R.id.baseUserButton); itemButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(ListViewActivity.this, "You click " + title + " , " + desc, Toast.LENGTH_SHORT).show(); } }); return itemView; } }; // Get the ListView object. ListView listView = (ListView)findViewById(R.id.listViewExample); // Set the custom base adapter to it. listView.setAdapter(customBaseAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) { Object clickItemObj = adapterView.getAdapter().getItem(index); HashMap clickItemMap = (HashMap)clickItemObj; String itemTitle = (String)clickItemMap.get("title"); String itemDescription = (String)clickItemMap.get("description"); Toast.makeText(ListViewActivity.this, "You select item is " + itemTitle + " , " + itemDescription, Toast.LENGTH_SHORT).show(); } }); } }
how can i add new column