Saturday, April 20, 2024
HomeAndroidAndroid ListView Tutorial with Example using Android Studio

Android ListView Tutorial with Example using Android Studio

-

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.android listview tutorial with example

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:

[widget id=”text-15″]

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.

  1. 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.
  2. Now Open activity_main.xml (or the xml created along with your Activity) and add the following code:
    <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-->
        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/list"/>
    
    </RelativeLayout>

    This code is pretty much basic – we just added an android listview to the default Relative Layout.

  3. 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.
  4. Now we open MainActivity.java and we wire up the android listview in xml file. We add the code as follows:
    package 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 ListView
        ListView mListView;
    
        //Elements that will be displayed in android ListView
        String[] 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 value
        int[] 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};
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mListView = (ListView) findViewById(R.id.list);
    
            //Declaring Array adapter
            ArrayAdapter<String> countryAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Countries);
    
            //Setting the android ListView's adapter to the newly created adapter
            mListView.setAdapter(countryAdapter);
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public 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 listview
                    int itemPosition = position;
    
                    //Get the String value of the item where the user clicked
                    String itemValue = (String) mListView.getItemAtPosition(position);
    
                    //In order to start displaying new activity we need an intent
                    Intent intent = new Intent(getApplicationContext(),CountryActivity.class);
    
                    //Putting the Id of image as an extra in intent
                    intent.putExtra("flag",FlagId[position]);
    
                    //Here we will pass the previously created intent as parameter
                    startActivity(intent);
    
                }
            });
        }
    
      
        @Override
        public 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;
        }
    
        @Override
        public 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 SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    }
    

    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.

    [widget id=”text-15″]

  5. 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.
  6. 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:
    <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">
    
    
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/ivCountryFlag"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />
    </RelativeLayout>
    

    [widget id=”text-3″]

  7. Now let’s wire up this ImageView element to the java class. We open CountryActivity.java and type the following code:
    package 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 {
    
        @Override
        protected 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);
        }
    
        @Override
        public 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;
        }
    
        @Override
        public 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 SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
    
            return super.onOptionsItemSelected(item);
        }
    }
    

    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.

     

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.

[widget id=”text-15″]

9 COMMENTS

  1. Hi. If I wanted a situation that when the user touches any Country it came up with a list of each state within that country, what’s the best way to do this. Would you do another List view?

  2. Dear Developer, thanks for valuable tutorial, I want to make list view and when we clic on item it open to new actvity, could you show because it didnot see your guide. Thanks in advance.

  3. Hi Vamsi, I was following your tutorial and noticed something. In line 47 of MainActivity.java, you have stored the value of position in a variable,’itemPosition’.But you have not used itemPosition at all…
    Is it necesary to have that line?

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

LATEST POSTS

Best Time to Buy and Sell Stock – Day 7 | 100 Days of Code

Welcome to Day 7 of 100 Days of Code where today we solve yet another most frequently asked easy array problem called - Best Time...

Contains Duplicate – Day 8 | 100 Days of Code

Welcome to Day 8 of 100 Days of Code and today we are going to solve yet another easy-level problem - Contains Duplicate as part...

Two Sum – Day 6 | 100 Days of Code

Welcome to Day 6 of 100 Days of Code where we solve the most frequently asked Easy level Array problem - Two Sum. Let us...

Embarking on a 100-day adventure: Day 5 – No.Of Occurrences In An Array

Welcome to Day 5 of our coding journey! Today, we dive deep into the world of programming to tackle a common, yet curious problem: finding...

Follow us

1,358FansLike
10FollowersFollow
401SubscribersSubscribe

Most Popular