Hello friends, here in this tutorial we are going to develop a small application using List View in which on selecting an item it will display the message that the respected item is selected.
- Steps are as follows:
- Create the MainActivity ie the java file and in the layout for example create an list_element.xml file and in values-> create new xml file called item_data.xml file .
- Now in item_data.xml files write down the list of items you want in your list.
- The image of the code is shown below:
- Once you finish with this go to the list_item.xml file and provide id for your text view i.e android:id=”@+id/fruitName”
- Now in the MainActivity file instead of extending Activity replace it with extending ListActivity.
- Using a String[] array we can get the Resources stored in our xml file.
- Now set the ListAdapter to new ArrayAdapter that contains (this , R.layout.list_element ,R .id.id of the text view and the array name) as shown below in the code :
- The code is as follows:
- Now run the code you will have the following output :
- Now you can scroll your list .
- If you want the list item to be selected and display the message the following changes are to be made in the respective code.
- In the onCreate( ) method use the ListView to get the View of the list by using:
ListView listview = getListView(); - Now with the listview as a object set the OnItemClickListener so that when you click on the items in the list it will select the clicked item.
- As mentioned above for clicking an item, update the following code:
- Toast.makeText() method is used for displaying and making the text.
- Now when you run the code will get the following output:
- So now when we select any item in the list it will display the message that respective item is selected.
[code language=”java”]
public class MainActivity extends ListActivity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[]fruits = getResources().getStringArray(R.array.fruits);
this.setListAdapter(new ArrayAdapter(
this ,
R.layout.list_item ,
R.id.fruitName, ,
fruits));
}
}
[/code]
[code language=”java”]
ListView listview = getListView();
listview.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View clickView, int position,long id)
{
// TODO Auto-generated method stub
String fruit = fruits[position];
Toast.makeText(MainActivity.this,String.format("%s Fruit is selected", fruit), Toast.LENGTH_SHORT).show();
}
[/code]