Android ListView Tutorial with Example using Android Studio:
Note: Android RecyclerView is the most advanced and recommended version of ListView. You can refer to the article on Android RecyclerView here.
In this Article we are going to discuss about how to implement a simple Android ListView with example using Android Studio. In this example we will create and display a list using default android Adapter and we display another activity when any item on the list is tapped.
Our main goal here is to display various Country names in the listview and when the user touches any Country name, a new Activity starts displaying that Country’s flag. The final output of the code looks as shown in the following video:
Let us dive into the tutorial.
Steps to create a simple Android ListView using Android Studio:
In this Simple Android ListView project, we need two activities – one to display the android listview and the other to display the country flag. Let us first start by creating the project.
- Create a New Android Studio Project by opening File > Close Projects > Start a New Android Studio Project and giving an appropriate Application name. I named the Application Name as Simple ListView. Select Blank Activity and hit Next and select Activity name. I kept mine as default – Now hit Finish.
- Now Open activity_main.xml (or the xml created along with your Activity) and add the following code:This code is pretty much basic – we just added an android listview to the default Relative Layout.1234567891011121314<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"><!-- Here we are defining ListView in our XML file--><ListViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:id="@+id/list"/></RelativeLayout>
- Next we need the country flags to display accordingly. You can use the flags provided from this project’s zip file attached to this tutorial or use your own images. Place them in your Res> Drawable folder.
- Now we open MainActivity.java and we wire up the android listview in xml file. We add the code as follows:The code is commented whereever it is necessary. Here we discuss about it in detail. After inflating the layout in Line 34, we set up a reference variable mListView and wire it up with listview. Thereafter we declare an Array Adapter. This adapter takes three parameters -context, resource and array of objects. This adapter acts as a bridge between the list and adapterview. We next declare an Intent to Start second Activity which I’ve named as CountryActivity.java. Now we pass the value of the resource value based on the item clicked to the next activity via putExtra() method of intent. Next we start another activity using startActivity(intent) method.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687package com.coderefer.simplelistview;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.Toast;public class MainActivity extends AppCompatActivity {//Defining android ListViewListView mListView;//Elements that will be displayed in android ListViewString[] Countries = new String[]{"India", "Australia", "Newzealand","Indonesia", "China", "Russia", "Japan", "South Korea"};//Ids of flag Images that are placed in res> drawable folder. They return the int valueint[] FlagId = new int[]{R.drawable.flag_india, R.drawable.flag_australia,R.drawable.flag_newzealand,R.drawable.flag_indonesia,R.drawable.flag_china, R.drawable.flag_russia,R.drawable.flag_japan,R.drawable.flag_southkorea};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mListView = (ListView) findViewById(R.id.list);//Declaring Array adapterArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Countries);//Setting the android ListView's adapter to the newly created adaptermListView.setAdapter(countryAdapter);mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {//The position where the list item is clicked is obtained from the//the parameter position of the android listviewint itemPosition = position;//Get the String value of the item where the user clickedString itemValue = (String) mListView.getItemAtPosition(position);//In order to start displaying new activity we need an intentIntent intent = new Intent(getApplicationContext(),CountryActivity.class);//Putting the Id of image as an extra in intentintent.putExtra("flag",FlagId[position]);//Here we will pass the previously created intent as parameterstartActivity(intent);}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}
- Now we need to create another activity which will be shown when user clicks an item from the android listview. We can create a new Activity by Right clicking on the package name and selecting New>Activity>Blank Activity. I’ve named my new activity as CountryActivity.java and the corresponding xml as activity_country.xml.
- Now let us modify activity_country.xml first. We need to display the corresponding country flag in this layout. So the element we need is an ImageView which will be filled according to the country the user pressed. Now we modify the activity_country.xml as follows:12345678910111213141516<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="@dimen/activity_vertical_margin"tools:context="com.coderefer.simplelistview.CountryActivity"><ImageViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/ivCountryFlag"android:layout_centerVertical="true"android:layout_centerHorizontal="true" /></RelativeLayout>
- Now let’s wire up this ImageView element to the java class. We open CountryActivity.java and type the following code:Here we obtained the reference to the imageview in line 17 and we also retrieved the resource data in line 20 from the intent by providing the key “flag”. Now we set the imageview in line 21 using the resource data we retrieved.123456789101112131415161718192021222324252627282930313233343536373839404142434445package com.coderefer.simplelistview;import android.content.Intent;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.ImageView;public class CountryActivity extends ActionBarActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_country);ImageView imageView = (ImageView) findViewById(R.id.ivCountryFlag);Intent i = getIntent();int FlagId = i.getIntExtra("flag",0);imageView.setImageResource(FlagId);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_country, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}
Now we can successfully run the Project and Display the List of Countries. If any of the country name is clicked, a new activity starts displaying the corresponding country’s flag. In the next tutorial we will discuss about custom android listview.