Android simple & custom List views with examples
Android List Views are like any other lists where we have a series of items aligned in a vertical fashion. In Android List Views are used in many ways, most likely as Menu’s to navigate to different screens. Generally list views are used to show a single or multiple lines of text as the list items but we can customize the list view to show a layout ( for ex: containing a thumbnail a Text Heading and and another Text to show the description) as the list item.
Lets start with creating a simple List View:
Simple List View example:
Lets create a Simple List View with a list of strings and showing a ‘Toast’ on clicking the particular List item:
The final out put will look like this:
Hers are the steps to create a Simple List View:
step 1: Create a new Project with a blank Activity(‘MainActivity.java’).
step 2: Open the main activity class file (‘MainActivity.java’ in my case), You can see that it extends an ‘Activity’ but for creating a simple list view we need to extend the ‘ListActivity’, change the code accordingly:
public class MainActivity extends ListActivity { . . . }
step 3: We need to have a set of strings to feed the list view, so create a string array[] with some name (listItems[] in my case):
String listItems[] = { "List Item 1", "List Item 2", "List Item 3", "List Item 4", "List Item 5", "List Item 6", "List Item 7", "List Item 8", "List Item 9", "List Item 10", "List Item 11", "List Item 12" };
step 4: List View requires an Adapter to feed the list, create an Array adapter with the array we created in the last step:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
step 6: All set now! we need to set the main view, Generally we set the views from the layout file (setContentView()) but here we don’t require a Layout so set the List Adapter(setListAdapter(adapter)):
setListAdapter(adapter);
Now Run the application and you can see a list with all the items in the Array. But here nothing happens when you click on the list items. To perform an action on the list item click, we need to set a Listener() to the ListView, As we are extending the ListActivity we can implement the ListActivity methods directly by Rightclicking in the editor > ‘Source’ > ‘Override/Implement Methods..’. > Under ‘ListActivity’ > Select ‘onListItemClickListner()’ > Click ‘OK’ :
@Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); //Display a toast on item clicked in the List Toast toast = Toast.makeText(this, "You clicked on: " + listItems[position], Toast.LENGTH_SHORT); toast.show(); }
onListItemClick() method gives you the position of the list item clicked. With the position got display the ‘Toast’ with the respective title from the Array ( listItems[position] ).
The final code will look as follows:
public class MainActivity extends ListActivity { //Create an array of list items private String listItems[] = { "List Item 1", "List Item 2", "List Item 3", "List Item 4", "List Item 5", "List Item 6", "List Item 7", "List Item 8", "List Item 9", "List Item 10", "List Item 11", "List Item 12" }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Create ArrayAdapter using the array(listItems) ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems); //Set the ArrayAdapter as the ListView's adapter setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); //Display a toast on item clicked in the List Toast toast = Toast.makeText(this, "You clicked on: " + listItems[position], Toast.LENGTH_SHORT); toast.show(); } }
Done!! Run the App and see the result.
Custom List View:
Lets create a custom List view with list items containing a thumbnail and and some text. The final out put is shown below:
Here’s the steps to create the Custom List View:
step 1: Create a new Project with a blank Activity.
step 2: Create the main layout (activity_main.xml) with a list view as shown below:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@+id/listView" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" > </ListView> </LinearLayout>
step 3: Create a layout for the list item (list_item.xml) as shown below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="5dp" > <ImageView android:id="@+id/thumb" android:layout_width="80dp" android:layout_height="80dp" android:contentDescription="@string/app_name" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:layout_marginRight="5dp" android:layout_toLeftOf="@+id/arrow" android:layout_toRightOf="@+id/thumb" android:orientation="vertical" > <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/title" android:textSize="16dp" android:textStyle="bold" /> <TextView android:id="@+id/desc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:text="@string/desc" android:textSize="12dp" /> </LinearLayout> <ImageView android:id="@+id/arrow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="5dp" android:contentDescription="@string/app_name" android:src="@drawable/arrow_next" /> </RelativeLayout>
step 4:
Create a Main Class Activity (MainActivity.java) as shown below:
public class MainActivity extends Activity { private ListView lv; // Create Array's of titles, descriptions and thumbs resource id's: private String title[] = { "Cup Cake", "Donut", "Eclair", "Froyo", "Ginger Bread", "Honey Comb", "Icecream Sandwich", "Jelly Bean" }; private String desc[] = { "version: 1.5", "version: 1.6", "version: 2.0 & 2.1", "version: 2.2", "version: 2.3", "version: 3.0", "version: 4.0", "version: 4.1" }; private int thumb[] = { R.drawable.cupcake, R.drawable.donut, R.drawable.eclair, R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.icecreamsandwich, R.drawable.jellybean, }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize the variables: lv = (ListView) findViewById(R.id.listView); // Set an Adapter to the ListView lv.setAdapter(new VersionAdapter(this)); // Set on item click listener to the ListView lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // actions to be performed when a list item clicked int pos = arg2; LayoutInflater layoutInflator = getLayoutInflater(); View layout = layoutInflator.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root)); ImageView iv = (ImageView) layout.findViewById(R.id.toast_iv); TextView tv = (TextView) layout.findViewById(R.id.toast_tv); iv.setBackgroundResource(thumb[pos]); tv.setText(title[pos]); Toast toast = new Toast(getApplicationContext()); toast.setView(layout); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); } // Create an Adapter Class extending the BaseAdapter class VersionAdapter extends BaseAdapter { private LayoutInflater layoutInflater; public VersionAdapter(MainActivity activity) { // TODO Auto-generated constructor stub layoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // Set the count value to the total number of items in the Array return title.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // Inflate the item layout and set the views View listItem = convertView; int pos = position; if (listItem == null) { listItem = layoutInflater.inflate(R.layout.list_item, null); } // Initialize the views in the layout ImageView iv = (ImageView) listItem.findViewById(R.id.thumb); TextView tvTitle = (TextView) listItem.findViewById(R.id.title); TextView tvDesc = (TextView) listItem.findViewById(R.id.desc); // Set the views in the layout iv.setBackgroundResource(thumb[pos]); tvTitle.setText(title[pos]); tvDesc.setText(desc[pos]); return listItem; } } }
step 5: Lets display a ‘Custom Toast’ with an image and text on click of the list item:
Creating custom Toast:
It’s quite simple create a layout with the desired elements to show in the ‘Toast’, in my case a main/root layout an image view and a text view:
custom_toast.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout_root" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#DAAA" android:orientation="vertical" android:padding="8dp" > <ImageView android:id="@+id/toast_iv" android:layout_width="120dp" android:layout_height="120dp" android:layout_gravity="center_horizontal" android:contentDescription="@string/app_name" /> <TextView android:id="@+id/toast_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textColor="#FFF" /> </LinearLayout>
Create a view by inflating the layout and attach that to the Toast by toast.setView(view):
LayoutInflater layoutInflator = getLayoutInflater(); View layout = layoutInflator.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root)); ImageView iv = (ImageView) layout.findViewById(R.id.toast_iv); TextView tv = (TextView) layout.findViewById(R.id.toast_tv); iv.setBackgroundResource(thumb[pos]); tv.setText(title[pos]); Toast toast = new Toast(getApplicationContext()); toast.setView(layout); toast.setGravity(Gravity.CENTER, 0, 0); toast.show();
Also refer:
http://developer.android.com/guide/topics/ui/notifiers/toasts.html#CustomToastView