How to use ListView and GridView in Java

766 Views

In this article, you will learn how to implement ListView and GridView in an Android application with Android Studio.

PLEASE NOTE: This tutorial has been written using Android Studio 3.5.x and Java

The Android project

Let’s start by creating a new project. Open Android Studio and click + Start a new Android Studio project.

Select the Empty Activity and click the Next button.

Type a name for your project – I’ve set ListGridView for the sake of this tutorial.

When you set an Android Studio’s project name, it’s always good to leave no spaces between words.

Type the package name you want for your application, select the location of the files and click the Finish button.

When Android Studio will be done on creating your project, expand the res/layout folder, in order to access the activity_main.xml file. Double click on it to edit.

The first thing we need to do in this XML file is to change the current ConstraintLayout into a RelativeLayout. So click the Text tab on the bottom of the window to enter the code editor – you are now seeing the Design editor area, we’ll go back to this tab in a little while.

Select this line:

androidx.constraintlayout.widget.ConstraintLayout

And start typing RelativeLayout. A popup will show up showing you the completeness of what you’re typing. Just hint Enter on the keyboard to confirm the selection, and your change will be applied.

Select the whole <TextView ... > tab and its content simply delete it. So now we finally have an empty screen to edit as we wish. Let’s do that in the Design editor, so click the Design tab.

ListView and custom cell design

I want to start by implementing a ListView, later we’ll see how to build a GridView by adding a new Java class + its relative layout.

In the Design area, check out the Palette panel. Click the search lens to search for ListView.

Drag the found ListView widget into the layout screen. Android Studio will automatically set its width and height properties as match_parent, which means that our ListView’s edges will stick to the screen’s edges of our Android device.

Let’s give an ID name to our ListView, it’s important because we’ll call it in the MainActivity.java file to initialize it and make our app recognize our ListView by its ID. Type myListView in the id field on the right-side panel – that’s the Attributes inspector.

Before creating a custom cell, we may set a couple of more attributes for our ListView, the divider’s height and color. You can find both fields right below the background one. I want to make the cells separator’s color as #e1e1e1 – light gray – and its height of 1dp.

We’re done with the ListView’s attributes, let’s now create a cell that we’ll use to display our data as a list. Place your mouse pointer over the layout folder, right-click on it and select New -> Layout Resource File.

In the popup window that will show up, type cell_listview in the File name field and change LinearLayout into RelativeLayout in the Root element filed.

We need a Relative Layout for our custom cell in order to be free to place Views wherever we want. A Linear Layout forces our Views to get aligned only horizontally or vertically.

Naming layout XML files in Android Studio is pretty srrict, you cannot use uppercase characters, but only lowercase ones and underscores as word separators. That’s why I’ve named our custom cell as cell_listview.
The same thing applies to all files and resources stored in the res folder.

When you’re done, click the OK button.

Android Studio will open the cell_listview layout file in the Design tab.
Let’s start by searching for a TextView widget in the Palette panel and dragging it into our screen. It will automatically get positioned on the top-left corner of the layout, so we have to adjust its attributes by using the panel on the right-side of the screen again.
First, give our TextView an Id, then change its layout_width property into match_parent.
Click the lens icon and search for margin, so the layout_margin propery will show up in the list. Expand it and type 10dp the layout_marginTop and layout_marginEnd fields. In the layout_marginStart, insert 80dp.
This is the final result:

Now drag an ImageView widget from the Palette tab into the layout screen. When you’ll release the mouse button, a popup will show up. In this step, we are forced to choose and image or a color, so expand the Project tab and select the ic_launcher icon, then click the OK button.

Of course, we’ll use a set of images for our project – they can be downloaded here.
Once you’ve downloaded the demo images, extract the zip file and move your mouse pointer over the drawable folder in Android Studio, right-click on it and select the Reveal In Finder option.
Enter the drawable folder and drag the jpg images from the demo_images folder you just extracted into the drawable folder.

Go back to the cell_listview layout, select the ImageView and set its Attributes as shown below. Remember that you may use the lens icon to search for margin again and set the layout margins of our ImageView.

In case you’d rather using the code to design this cell, here’s what you can use inside the Text tab of our cell_listview.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:id="@+id/cell_myTxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="80dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:text="TextView" />

    <ImageView
        android:id="@+id/cell_img"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:scaleType="centerCrop"
        app:srcCompat="@mipmap/ic_launcher" />
</RelativeLayout>

Everything is ready about deigning our ListView and its relative custom cell.

ListView code

Let’s make our ListView alive by writing some code in the MainActivity.java file. The very first thing to do is to declare the ListView outside the onCreate() function, right below the class declaration:

ListView myListView;

Then, inside the onCreate() function, initialize the ListView:

myListView = findViewById(R.id.myListView);

Before creating a ListAdapter – needed to handle our ListView’s data – we have to create a List<String> array and a Context variable. Declare them right below the myListView declaration:

List<String> myItems = new ArrayList<>();
 Context ctx = this;

Inside onCreate(), build the myItems array as it follows:

myItems.add("New York");
 myItems.add("Dublin");
 myItems.add("Los Angeles");
 myItems.add("Dubai");
 myItems.add("London");

We just populated the myItems array with 5 elements that will be displayed in our ListView once we’ll be done coding.

It’s time to create a ListAdapter, where we will initialize the cell_listview‘s views and let them show a set of strings and images.
Place this code outside the onCreate() function, but before the class’ closure:

   void showDataInListView() {
      class ListAdapter extends BaseAdapter {
         private Context context;
         private ListAdapter(Context context) {
            super();
            this.context = context;
         }

         @SuppressLint("InflateParams")
         @Override
         public View getView(int position, View cell, ViewGroup parent) {
            if (cell == null) {
               LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
               assert inflater != null;
               cell = inflater.inflate(R.layout.cell_listview, null);
            }

            //-----------------------------------------------
            // MARK - INITIALIZE VIEWS
            //-----------------------------------------------
            TextView cellTxt = cell.findViewById(R.id.cell_myTxt);
            ImageView cellImg = cell.findViewById(R.id.cell_img);

            // Set text
            cellTxt.setText(myItems.get(position));

            // Set the image, based on its name
            int imgID = getResources().getIdentifier("img_" + position, "drawable", getPackageName());
            cellImg.setImageResource(imgID);

         return cell;
         }

         @Override public int getCount() { return myItems.size(); }
         @Override public Object getItem(int position) { return myItems.get(position); }
         @Override public long getItemId(int position) { return position; }
      }

      // Set Adapter
      myListView.setAdapter(new ListAdapter(ctx));


      //-----------------------------------------------
      // MARK - TAP A CELL
      //-----------------------------------------------
      myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
         public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            // Show a Toast message of the selected cell
            Toast.makeText(ctx, myItems.get(position), Toast.LENGTH_SHORT).show();
      }});
 }

You’ll surely have to import something, so you’ll see some instances in red color. Don’t worry, just place the mouse pointer over a red instance – like BaseAdapter, for instance – hold the alt key and press Enter. Android Studio will import the selected instance on the top of the java file, in the imports list.

Once you’ll be done, run the app and see our ListView in action. If you tap the Los Angeles row, you should get something like this:

GridView design

Let’s now design a GridView and its custom cell. We’ll need to create a new Activity so right-click on the package name of your project – in the left-side files list – select New -> Activity -> Empty Activity.

In the Activity Name field, type a no-spaces name like GridViewActivity and click the Finish button.

Create a new Activity

Let Android Studio sync Gradle before opening any layout of java file. This will also declare your new Activity into the Manifest file.

Once the software is ready and the yellow notification on the top of the screen disappeared, enter the Text tab of the activity_grid_view.xml file and, as we’ve previously done for the activity_main.xml file, replace ConstraintLayout with RelativeLayout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".GridViewActivity">

</RelativeLayout>

Switch to the Design tab, search for GridView in the Palette tab and drag it into our layout screen.
Give it an id like myGridView.

Right-click over the layout folder again to create a new Layout resource file, as you did for the cell_listview. This time, call the new layout as cell_gridview.

Stay in the Design area and start building it by dragging an ImageView widget into it. This time you may search for img_0 and set it as default image.

Set its Attributes and id as shown below:

Add a TextView into the cell_gridview layout and set its id, margins and constraints as shown below:

If you want to code instead, here’s what you can paste in the Text tab of our cell_gridview.xml file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <ImageView
        android:id="@+id/cellGvImg"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:scaleType="centerCrop"
        app:srcCompat="@drawable/img_0" />

    <TextView
        android:id="@+id/cellGvTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/cellGvImg"
        android:layout_alignEnd="@+id/cellGvImg"
        android:layout_alignParentStart="true"
        android:layout_marginTop="5dp"
        android:text="TextView"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="12sp"
        android:textStyle="bold" />
</RelativeLayout>

GridView code

Time to code again, so enter the GridViewActivity.java file and declare a GridView right above the onCreate() function:

GridView myGridView;

Initialize it inside the onCreate() function:

myGridView = findViewById(R.id.myGridView);

Now you may re-open the MainActivity.java, copy these 2 variables and paste them into GridViewActivity.java:

List<String> myItems = new ArrayList<>();
 Context ctx = this;

And back to the onCreate() method, paste the same code you’ve set in the other java file:

myItems.add("New York");
 myItems.add("Dublin");
 myItems.add("Los Angeles");
 myItems.add("Dubai");
 myItems.add("London");

 // Call function
 showDataInGridView();

We’ll be using the same array if cities we built for the ListView – myItems – but this time the look of our app will be different than before, of course, that’s because we’re going to use a GridView 🙂

One last thing to do is to paste the following function outside the onCreate() function:

 void showDataInGridView() {
      // Set number of columns
      final int numberOfColumns = 2;

      class GridAdapter extends BaseAdapter {
         private Context context;

         private GridAdapter(Context context) {
            super();
            this.context = context;
         }

         @SuppressLint("InflateParams")
         @Override
         public View getView(int position, View cell, ViewGroup parent) {
            if (cell == null) {
               LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
               assert inflater != null;
               cell = inflater.inflate(R.layout.cell_gridview, null);
            }
            //-----------------------------------------------
            // MARK - INITIALIZE VIEWS
            //-----------------------------------------------
            TextView cellTxt = cell.findViewById(R.id.cellGvTxt);
            ImageView cellImg = cell.findViewById(R.id.cellGvImg);

            // Set cell size
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((Activity) ctx).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int width = displayMetrics.widthPixels;
            cellImg.getLayoutParams().width = width / numberOfColumns;
            cellImg.getLayoutParams().height = width / numberOfColumns;

            cellTxt.setText(myItems.get(position));

            int imgID = getResources().getIdentifier("img_" + position, "drawable", getPackageName());
            cellImg.setImageResource(imgID);


         return cell;
         }
         @Override public int getCount() { return myItems.size(); }
         @Override public Object getItem(int position) { return myItems.get(position); }
         @Override public long getItemId(int position) { return position; }
      }

      // Set Adapter
      myGridView.setAdapter(new GridAdapter(ctx));
      myGridView.setNumColumns(numberOfColumns);


      //-----------------------------------------------
      // MARK - TAP A CELL
      //-----------------------------------------------
      myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
             // Show Toast for selected cell
             Toast.makeText(ctx, myItems.get(position), Toast.LENGTH_SHORT).show();
      }});

 }

As you may notice, the code inside the GridAdapter looks pretty similar to the one used in the ListViewAdapter of the MainActivity.java file. The main difference comes from the usage of the DisplayMetrics instance, which calculates the size of the device screen and displays the ImageViews as square size in the GridView.

So, in order for you to see your GrdiView in action, you need to open the Manifest.xml file and replace this line:

<activity android:name=".MainActivity">

with:

<activity android:name=".GridViewActivity">

Also, replace:

<activity android:name=".GridViewActivity"></activity>

with:

<activity android:name=".MainActivity"></activity>

In this way, you’ll set the GridViewActivity as the first screen at app startup.

Run your app now and you should get something like this:

GridView on an Android device

Conclusion

That’s all for this tutorial, you have learned how to create a ListView and a GridView for your next awesome Android applications.

Hope you enjoyed this article, feel free to post comments about it. You can also download the full Android Studio project of this article, just click the link below:

Download the Android Studio project

Buy me a coffee - XScoder - thanks for your support
Your support will be highly appreciated 😉