Android Lesson 7 – part 2: work with ListView using a custom ArrayAdapter


In the previous tutorial, we learn how to use ListView using a basic ArrayAdapter.

Now we learn how to use ListView using a custom ArrayAdapter.

Step 1: create new project
Step 2: Define new Model
In file MainActivity.java

public class City {
        public String serverID;
        public String name;
        public City(String serverID, String name) {
            this.serverID = serverID;
            this.name = name;
        }
    }

Step 3: create new layout xml file
res\layout\item.xml. We create 3 TextView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/serverID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="server ID" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text=":"
        android:id="@+id/textView" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="name" />
</LinearLayout>

android create new resource file

Step 4: Define the custom Adapter
In file MainActivity.java

   public class CityAdapter extends ArrayAdapter<City> {
        public CityAdapter(Context context, ArrayList<City> cities) {
            super(context, 0, cities);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Get the data item for this position
            City city = getItem(position);
            // Check if an existing view is being reused, otherwise inflate the view
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
            }
            // Lookup view for data population
            TextView serverID = (TextView) convertView.findViewById(R.id.serverID);
            TextView name = (TextView) convertView.findViewById(R.id.name);
            // Populate the data into the template view using the data object
            serverID.setText(city.serverID);
            name.setText(city.name);
            // Return the completed view to render on screen
            return convertView;
        }
    }

Step 5: Attach the custom Adapter to a ListView
In file MainActivity.java, in method onCreate:

listView = (ListView) findViewById(R.id.listView);

        // Construct the data source
        ArrayList<City> arrayOfCities = new ArrayList<City>();

        arrayOfCities.add(new City("sv1","London"));
        arrayOfCities.add(new City("sv2","Manchester"));
        arrayOfCities.add(new City("sv3","Newyork"));
        arrayOfCities.add(new City("sv4","Toronto"));
        arrayOfCities.add(new City("sv5","Athen"));

        // Create the adapter to convert the array to views
        CityAdapter adapter = new CityAdapter(this, arrayOfCities);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                City cityselected = (City) listView.getItemAtPosition(i);
                //String serverID = cityselected.serverID;
                String name = cityselected.name;
                Toast.makeText(getApplicationContext(), "City selected: " + name, Toast.LENGTH_LONG).show();
            }
        });

Step 6: Run, we’ll get the result

android custom arrayadapter

Here’s the full code of file MainActivity.java

package com.tutorialspots.listview;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    public ListView listView;

    public class City {
        public String serverID;
        public String name;
        public City(String serverID, String name) {
            this.serverID = serverID;
            this.name = name;
        }
    }

    public class CityAdapter extends ArrayAdapter<City> {
        public CityAdapter(Context context, ArrayList<City> cities) {
            super(context, 0, cities);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Get the data item for this position
            City city = getItem(position);
            // Check if an existing view is being reused, otherwise inflate the view
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
            }
            // Lookup view for data population
            TextView serverID = (TextView) convertView.findViewById(R.id.serverID);
            TextView name = (TextView) convertView.findViewById(R.id.name);
            // Populate the data into the template view using the data object
            serverID.setText(city.serverID);
            name.setText(city.name);
            // Return the completed view to render on screen
            return convertView;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        listView = (ListView) findViewById(R.id.listView);

        // Construct the data source
        ArrayList<City> arrayOfCities = new ArrayList<City>();

        arrayOfCities.add(new City("sv1","London"));
        arrayOfCities.add(new City("sv2","Manchester"));
        arrayOfCities.add(new City("sv3","Newyork"));
        arrayOfCities.add(new City("sv4","Toronto"));
        arrayOfCities.add(new City("sv5","Athen"));

        // Create the adapter to convert the array to views
        CityAdapter adapter = new CityAdapter(this, arrayOfCities);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                City cityselected = (City) listView.getItemAtPosition(i);
                //String serverID = cityselected.serverID;
                String name = cityselected.name;
                Toast.makeText(getApplicationContext(), "City selected: " + name, Toast.LENGTH_LONG).show();
            }
        });
    }
...
}

Leave a Reply