ListView:
ListView is used to show more than one item of the similar type of data.
To work with ListView, we have following steps.
1) Provide id in XML
2) Identify in Java
3) Identify the items to show in ListView
4) Create an adapter with the items – 2 types of adapters
Basic adapter
Custom Adapter
5) Set that adapter to ListView
6) Setlist item click and handle the clicks
Ex:
<ListView
android:id=”@+id/listView”
android:layout_width=”match_parent”
android:layout_height=”match_parent” />
In Java
ListView listView = (ListView) findViewById(R.id.listView);
String[] items = {“One”, “Two”, “Three”, “Four”, “Five”, “Six”, “Seven”}; // Identifying items
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView2, items); // Creating an Adapter
listView.setAdapter(arrayAdapter); // Setting adapter to ListView
In Adapter, we can provide our xml file with id as second and third parameters.
Handling item click in ListView:
To handle item click in ListView, we set OnItemClickListener to ListView.
Ex:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, position+” is clicked”, Toast.LENGTH_LONG).show();
}
});
1) Create an Android application with one ListView in first Activity, on clicking item in ListView, go to the second activity and show which item is clicked in first activity in a text view
Creating a custom adapter for ListView:
1) Create a subclass of BaseAdapter
2) Override 4 methods of BaseAdapter