Implementing ListView In Android

0
1908

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:
  1. 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 .
  2. Now in item_data.xml files write down the list of items you want in your list.
  3. The image of the code is shown below:
  4. 1.

  5. 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”
  6. Now in the MainActivity file instead of extending Activity replace it with extending ListActivity.
  7. Using a String[] array we can get the Resources stored in our xml file.
  8. 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:

    [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]

  9. Now run the code you will have the following output :
  10. 2.

  11. Now you can scroll your list .
  12. If you want the list item to be selected and display the message the following changes are to be made in the respective code.
  13. In the onCreate( ) method use the ListView to get the View of the list by using:
    ListView listview = getListView();
  14. 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.
  15. As mentioned above for clicking an item, update the following code:
  16. [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]

  17. Toast.makeText() method is used for displaying and making the text.
  18. Now when you run the code will get the following output:
  19. 3

  20. So now when we select any item in the list it will display the message that respective item is selected.