Controls - List Views (List and spinner)
×
Home Courses Community Support
Gray Matter

First Step Towards Android: Introduction »

Understanding Activities and Intents »

Hands On With UI Designing In Android (Controls-Views,Widgets and Layouts) »

Updating... »

Controls - List Views (List and spinner)

List Views: ListView and SpinnerView

List views are views that enable you to display a long list of items. In Android, there are two types of list views: ListView and SpinnerView. Both are useful for displaying long lists of items. The following sections show how to make use of these views in your activity.


ListView

The ListView displays a list of items in a vertically scrolling list. To understand it in a better manner let's take an example.

 

To see the List View follow these steps-

Step1: Create a new Android project and name it ListViews.

Step2: Now we will modify MainActivity.java file. So add the following code into MainActivity.java file-
 

package com.example.listviews;


import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String[] presidents = {
"Rajendra Prasad",
"Sarvepalli Radhakrishnan",
"Zakir Husain",
"Varahagiri Venkata Giri",
"Mohammad Hidayatullah",
"Varahagiri Venkata Giri",
"Fakhruddin Ali Ahmed",
"Basappa Danappa Jatti",
"Neelam Sanjiva Reddy",
"Giani Zail Singh",
"Shankar Dayal Sharma",
"Kocheril Raman Narayanan",
"A. P. J. Abdul Kalam",
"Pratibha Patil",
"Pranab Mukherjee"
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, presidents));
}
public void onListItemClick(
ListView parent, View v, int position, long id)
{
Toast.makeText(this,
"You have selected " + presidents[position],
Toast.LENGTH_SHORT).show();
}
}

 

Step3: Now Press F11 key to debug the application on the Android Emulator or on the device. Let's see the output window now-
 

 

Above figure shows the activity displaying the list of names of presidents of india. You can scroll down to see all the names.
 


 

Click on an item (any name). A message containing the item selected will be displayed.
 

 

Customizing the ListView

The ListView is a versatile control that you can further customize. In this section you will learn how you can allow multiple items in the ListView to be selected and how you can enable filtering support.  To understand it in a better manner let's take an example.
 

To customized the ListView follow these steps we are going to use the same project created earlier-
 

Step1: We will modify MainActivity.java file. So add the following code into MainActivity.java file-
 

package com.example.listviews;


import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String[] presidents = {
"Rajendra Prasad",
"Sarvepalli Radhakrishnan",
"Zakir Husain",
"Varahagiri Venkata Giri",
"Mohammad Hidayatullah",
"Varahagiri Venkata Giri",
"Fakhruddin Ali Ahmed",
"Basappa Danappa Jatti",
"Neelam Sanjiva Reddy",
"Giani Zail Singh",
"Shankar Dayal Sharma",
"Kocheril Raman Narayanan",
"A. P. J. Abdul Kalam",
"Pratibha Patil",
"Pranab Mukherjee"
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
ListView lstView = getListView();
//lstView.setChoiceMode(0); //CHOICE_MODE_NONE
//lstView.setChoiceMode(1); //CHOICE_MODE_SINGLE
lstView.setChoiceMode(2); //CHOICE_MODE_MULTIPLE
lstView.setTextFilterEnabled(true);

setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, presidents));
}
public void onListItemClick(
ListView parent, View v, int position, long id)
{
	//---toggle the check displayed next to the item---
	parent.setItemChecked(position, parent.isItemChecked(position));
Toast.makeText(this,
"You have selected " + presidents[position],
Toast.LENGTH_SHORT).show();
}
}

 

Step2: Now Press F11 key to debug the application on the Android Emulator or on the device. Let's see the output window now.
 

 

You can now click on each item to display the check icon next to it. Once the item is selected you'll see a message that says the respective item is selected. Also you can scrol the list if you want.

 

 

 

Storing items in the Strings.xml file

In the previous example we have seen that the list of presidents’ names is stored in an array, in a real-life application it is recommended that you either retrieve them from a database or at least store them in the strings.xml file. So, we are going to use the same project created earlier and we will store the itmes in the strings.xml file.

 

To store the items in the strings.xml file follow these steps-

Step1: We will modify strings.xml file which is located in the res/values directory. So add the following code into strings.xml file-
 

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ListViews</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    
<string-array name="presidents_array">
<item>Rajendra Prasad</item>
<item>Sarvepalli Radhakrishnan</item>
<item>Zakir Husain</item>
<item>Varahagiri Venkata Giri</item>
<item>Mohammad Hidayatullah</item>
<item>Varahagiri Venkata Giri</item>
<item>Fakhruddin Ali Ahmed</item>
<item>Basappa Danappa Jatti</item>
<item>Neelam Sanjiva Reddy</item>
<item>Giani Zail Singh</item>
<item>Shankar Dayal Sharma</item>
<item>Kocheril Raman Narayanan</item>
<item>A. P. J. Abdul Kalam</item>
<item>Pratibha Patil</item>
<item>Pranab Mukherjee</item>
</string-array>

</resources>


 

Step2: Now we will modify MainActivity.java file. So add the following code into MainActivity.java file-
 

package com.example.listviews;


import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String[] presidents ;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
ListView lstView = getListView();
//lstView.setChoiceMode(0); //CHOICE_MODE_NONE
//lstView.setChoiceMode(1); //CHOICE_MODE_SINGLE
lstView.setChoiceMode(2); //CHOICE_MODE_MULTIPLE
lstView.setTextFilterEnabled(true);

presidents =
getResources().getStringArray(R.array.presidents_array);

setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, presidents));
}
public void onListItemClick(
ListView parent, View v, int position, long id)
{
	//---toggle the check displayed next to the item---
	parent.setItemChecked(position, parent.isItemChecked(position));
Toast.makeText(this,
"You have selected " + presidents[position],
Toast.LENGTH_SHORT).show();
}
}


 

Step3: Now Press F11 key to debug the application on the Android Emulator or on the device. You should see the same list of names that appeared in the previous section.Let's see the output window now.
 


Also you can select the item similarly as you selected before.

 

SpinnerView

The ListView displays a long list of items in an activity, but sometimes you may want your user interface to display other views, and hence you do not have the additional space for a full-screen view like the ListView. In such cases, you should use the SpinnerView. The SpinnerView displays one item at a time from a list and enables users to choose among them.To understand it in a better manner let's take an example.

 

To see the SpinnerView follow these steps-

Step1: Create a new Android project and name it SpinnerView

Step2: We will modify activity_main.xml file which is located in the res/layout directory. So add the following code into activity_main.xml file-

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:drawSelectorOnTop="true"/>

</LinearLayout>

 

 

Step3: Now we will modify strings.xml file which is located in the res/values directory. So add the following code into strings.xml file-
 

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">SpinnerView</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    
    <string-array name="presidents_array">
<item>Rajendra Prasad</item>
<item>Sarvepalli Radhakrishnan</item>
<item>Zakir Husain</item>
<item>Varahagiri Venkata Giri</item>
<item>Mohammad Hidayatullah</item>
<item>Varahagiri Venkata Giri</item>
<item>Fakhruddin Ali Ahmed</item>
<item>Basappa Danappa Jatti</item>
<item>Neelam Sanjiva Reddy</item>
<item>Giani Zail Singh</item>
<item>Shankar Dayal Sharma</item>
<item>Kocheril Raman Narayanan</item>
<item>A. P. J. Abdul Kalam</item>
<item>Pratibha Patil</item>
<item>Pranab Mukherjee</item>
</string-array>

</resources>


 

Step4: Now we will modify MainActivity.java file. So add the following code into MainActivity.java file-
 

package com.example.spinnerview;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {
	String[] presidents;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        presidents =
        		getResources().getStringArray(R.array.presidents_array);
        		Spinner s1 = (Spinner) findViewById(R.id.spinner1);
        		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
        		android.R.layout.simple_spinner_item, presidents);
        		s1.setAdapter(adapter);
        		s1.setOnItemSelectedListener(new OnItemSelectedListener()
        		{
        		@Override
        		public void onItemSelected(AdapterView<?> arg0, View arg1,
        		int arg2, long arg3)
        		{
        		int index = arg0.getSelectedItemPosition();
        		Toast.makeText(getBaseContext(),
        		"You have selected item : " + presidents[index],
        		Toast.LENGTH_SHORT).show();
        		}
        		@Override
        		public void onNothingSelected(AdapterView<?> arg0) {}
        		});
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}


 

Step5: Now Press F11 key to debug the application on the Android Emulator or on the device. you will see a pop-up displaying the list of presidents’ names. Let's see the output window now.
 

 

 

Here you see one name is displayed so click on the arrow sign then you will see the output as-
 

 

Now click on any name. Clicking on an item will display a message showing you the item selected.
 


 

 

 

← Preview

Material Design (Animation, Style, Layout, Components, Patterns, Usability)

Next →

Updating...

NOTES

Our mission is to provide highly effective and quality education via innovative solutions. Geeksdemy look forward to bridge the gap between in-demand technology and academics in order to deliver innovative, easy, interesting and affordable learning across the Globe.

Courses

  • Python
  • Game Development with Unity 3D
  • Arduino
  • PCB & Circuit Designing
  • Robotics and Embedded C
  • 8051/8052 Embedded Systems
  • QuadCopter & UAV
  • MATLAB with Robotics
  • Raspberry Pi
Learn On the Go!
Get the Android App
Get the iOS App