In this tutorial, you will learn to make a list that will cover the entire screen. The list will become scrollable if items are exceeding the screen and the items can also be clicked and perform some action.
- In the layout file, create only a TextView.
- Above code is the complete layout file. There must not be any other view even any layout (RelativeLayout, LinearLayout etc.) present in the file.
- Open the .java file and write the following codes in onCreate() method.Create a string array containing the items that you want to show in the list.
- Set this array in the list adapter and thus the ListView will be created.
- Remove the setContentView() method from the onCreate() method as we have set the list adapter in spite of content view. Now run the application and see the result.
- To make the items clickable, write the following code.
public void onItemClick(AdapterView adapter,View view,int position,long id)
setOnItemClickListener() contains the method onItemClick() which is responsible for the actions of clicking on items. It contains following parameters-
- AdapterView- It is the list adapter whose item has been clicked.
- View- It is the item which has been clicked. To retrieve the text of the item, we cannot apply getText() method on object of class View. Thus it must be casted to (TextView) first and then we can use getText().
- Position- It is the position of the clicked item. Note that the position of first item is 0, not 1.
- Id- It is the id of the clicked item.