http://www.yogeshblogspot.com/android-custom-list-view-using-custom-adapter-example/



Android Custom List View using Custom Adapter Example-

ListView –

In the previous examples I have created ListView examples but those are very simple in nature so if you want to create a customized list view in which you want to add multiple View items then we must use our own defined custom adapter.

So in this application I want to create a list view in which each list item contains a image, and two text view.

Code Sample –

layout.xml

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

    <ImageView
        android:id="@+id/flag"
        android:layout_width="150sp"
        android:layout_height="150sp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/c1" />

    <TextView
        android:id="@+id/capital"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/flag"
        android:layout_marginBottom="27dp"
        android:layout_toRightOf="@+id/flag"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/capital"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="19dp"
        android:layout_marginTop="36dp"
        android:text="India"
        android:textSize="30sp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

In this file I am defining the layout of list view.so as per above xml file each list item contains aImageView and two TextViews.all the codes of this file is self explanatory.
So the next task is how to populate a List View by using this layout file.
For this task I am defining a custom adapter class.

CountryAdapter.java

package com.ui.yogeshblogspot;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CountryAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] countries;
private final String[] capitals=new String[]{"New Delhi","Copenhagen","Paris","Budapest","Tripoli","Moscow","Madrid","Washington, D.C."};

public CountryAdapter(Context ctx,String[] countries)
{
	super(ctx, R.layout.layout, countries);
	this.context = ctx;
	this.countries = countries;
	
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	// TODO Auto-generated method stub
	LayoutInflater inflator=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	View row=inflator.inflate(R.layout.layout, parent, false);
	TextView country=(TextView)row.findViewById(R.id.country);
	TextView capital=(TextView)row.findViewById(R.id.capital);
	ImageView flag=(ImageView)row.findViewById(R.id.flag);
	country.setText(countries[position]);
	String c=countries[position];
	if(c.equals("India"))
	{
		capital.setText("Capital-"+capitals[0]);
		flag.setImageResource(R.drawable.c1);
	}
	else if(c.equals("Denmark"))
	{
		capital.setText("Capital-"+capitals[1]);
		flag.setImageResource(R.drawable.c2);	
	}
	else if(c.equals("France"))
	{
		capital.setText("Capital-"+capitals[2]);
		flag.setImageResource(R.drawable.c3);	
	}
	else if(c.equals("Hungary"))
	{
		capital.setText("Capital-"+capitals[3]);
		flag.setImageResource(R.drawable.c4);	
	}
	
	else if(c.equals("Libya"))
	{
		capital.setText("Capital-"+capitals[4]);
		flag.setImageResource(R.drawable.c5);	
	}
	else if(c.equals("Russia"))
	{
		capital.setText("Capital-"+capitals[5]);
		flag.setImageResource(R.drawable.c6);	
	}
	else if(c.equals("Spain"))
	{
		capital.setText("Capital-"+capitals[6]);
		flag.setImageResource(R.drawable.c7);	
	}
	else if(c.equals("U.S."))
	{
		capital.setText("Capital-"+capitals[7]);
		flag.setImageResource(R.drawable.c8);	
	}
	
	return row;
}
}
 

This file is used to populate the List Items for ListView.in this file I am declaring two String array variables and these are.

private final String[] countries;
private final String[] capitals=new String[]
{"New Delhi","Copenhagen","Paris","Budapest","Tripoli","Moscow","Madrid","Washington, D.C."};

first array is countries. In this arrray I will store countries name. and second one is capitals array. in this array I am storing the names of capitals.and one thing is that I will pass the name of countries from Activity class.

Now lets discuss the remaining lines of Code.

public CountryAdapter(Context ctx,String[] countries)
{
	super(ctx, R.layout.layout, countries);
	this.context = ctx;
	this.countries = countries;
	
}

The above lines will initiate the Custom Adapter class.and also assigining the list of Countries.

Now lets discuss the getView() method.

In this file I am created the object of LayoutInflator class.LayoutInflator class is used to populate the View from XML file.


LayoutInflater inflator=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

In the next line of code I am populating View for each list item from the layout xml file.

View row=inflator.inflate(R.layout.layout, parent, false);

Now I am getting the reference of TextViews and ImageView to assign values.
So first I am getting the reference of country text view to assign the countries name and then getting the reference of capital text view to assign the names of capitals and then I am getting the flag image view.i will use this to assign the images of flags.

	TextView country=(TextView)row.findViewById(R.id.country);
	TextView capital=(TextView)row.findViewById(R.id.capital);
	ImageView flag=(ImageView)row.findViewById(R.id.flag);
	country.setText(countries[position]);
         String c=countries[position];
	if(c.equals("India"))
	{
		capital.setText("Capital-"+capitals[0]);
		flag.setImageResource(R.drawable.c1);
	}
	else if(c.equals("Denmark"))
	{
		capital.setText("Capital-"+capitals[1]);
		flag.setImageResource(R.drawable.c2);	
	}
	else if(c.equals("France"))
	{
		capital.setText("Capital-"+capitals[2]);
		flag.setImageResource(R.drawable.c3);	
	}
	else if(c.equals("Hungary"))
	{
		capital.setText("Capital-"+capitals[3]);
		flag.setImageResource(R.drawable.c4);	
	}
	
	else if(c.equals("Libya"))
	{
		capital.setText("Capital-"+capitals[4]);
		flag.setImageResource(R.drawable.c5);	
	}
	else if(c.equals("Russia"))
	{
		capital.setText("Capital-"+capitals[5]);
		flag.setImageResource(R.drawable.c6);	
	}
	else if(c.equals("Spain"))
	{
		capital.setText("Capital-"+capitals[6]);
		flag.setImageResource(R.drawable.c7);	
	}
	else if(c.equals("U.S."))
	{
		capital.setText("Capital-"+capitals[7]);
		flag.setImageResource(R.drawable.c8);	
	}

Then based on position I am assigning the name of country in country text view. and based on country with the help of if-else statements I am assigning the name of capital and images to the image view.

(PURPOSE OF THIS ADAPTER CLASS IS TO POPULATE LIST ITEMS)

Now let’s discuss the activity class.

CustomizedListViewExwithCustomAdapterActivity.java

package com.ui.yogeshblogspot;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class CustomizedListViewExwithCustomAdapterActivity extends ListActivity {
    /** Called when the activity is first created. */
	static final String[] COUNTRIES =new String[] { "India", "Denmark", "France", "Hungary","Libya","Russia","Spain","U.S."}; 
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setListAdapter(new CountryAdapter(this, COUNTRIES));
        
       
    }

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		String selectedValue = (String) getListAdapter().getItem(position);
		Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
	}
    
}

In this activity class I am creating String array with country names.
And inside the onCreate() method of this activity I am calling the setListAdapter() and passing the object of CountryAdapter().and inside the constructor of CountryAdapter class I am also passing the reference of current activity class and COUNTRIES list.

(SO JUST WAIT AND THINK HOW CUSTOM ADAPTER OBJECT IS INSTIATED (I HAVE ALREADY EXPLAINED HOW CUSTOM ADAPTER CLASS OBJECT IS POPULATED))

When we call the setListAdapter() method. List view automatically populated.

Then I am registering Item click listener in the list view to handle click listener.and inside the listener first I am getting the selected item and then based on selected item I am displaying a message using Toast.
List View