Payday Loan Payday Loan

How to create an Adapter for a Listview

Hi, this is my first tutorial here. I hope you’ll enjoy it. Ok, let’s start.

Let’s say that we want to create a Listview more different. We do not want to have only a small text, we want a button , a checkbox etc. in every Listview item. Here is a small tutorial where you can learn how to create an Adapter, the ” thing ” that will help us to personalize the ListView.

Ok, here is a small project where we’ll have:

-two classes : Listview.class (the class where we have  the Listview ) and the ListviewAdapter.class ( the class which cantains the adapter for the Listview, with its help will populate the Listview as we want )

-two XML files : one where is the Listview and one where is the “design ” for each item. I’ve named them listview.xml and listview_row.xml .

I’ve decided to create an Adapter for a Listview whose each item will contain two Textviews , one for Firstname other for Lastname.Here is the content that we’re interested in. I will explain it by adding comments in the Java code.

Listview.class :

public class Listview extends Activity {
 
	//Here are variables which contains the unique "keys", one for  every text in a single Listview row. 
	static final String KEY_FIRSTNAME = "firstname",KEY_LASTNAME="lastname";
 
	//Here are two arrays which contains some "interesting" words. Sorry, I had no inspiration.
	String[] firstname = {"Gates","Cheese","Apple","Computer","Noidea","Something","Bestintheworld"}; 
	String[] lastname = {"Tom","Dan","Andrew","Tyler","Austin","Jane","Bill"};
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview);
 
        //We declare the Listview. I had so much inspiration that I called it - listview .Yes, amazing.
        ListView listview = (ListView) findViewById(R.id.lvGenuine);
 
        //This arraylist stores all the the information that will be in the ListView
        ArrayList<HashMap<String, String>> myArrayList = new ArrayList<HashMap<String, String>>();
 
        //I need this " lenth" for the "for " part.
        int length = firstname.length;
 
 
        //I guess you know what this is.
        for(int i=0;i<length;i++){
 
        	// This hashmap stores the information that exists only in the item. 
        HashMap<String, String> blablabla  = new HashMap<String, String>();
		blablabla.put(KEY_FIRSTNAME, firstname[i]);
		blablabla.put(KEY_LASTNAME, lastname[i]);
 
		//we save the hashmap in the ArrayList . Big thing retains the small one.
		myArrayList.add(blablabla);
 
        }
 
        //We declare the adapter using the other class
        ListviewAdapter adapter = new ListviewAdapter(this,myArrayList);
        //We set the adapter, here is the "place" where we populate the List.
        listview.setAdapter(adapter);
 
    }
}

ListviewAdapter.class:

public class ListviewAdapter extends BaseAdapter {//To create an adapter we have to extend BaseAdapter instead of Activity, or whatever.
 
    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
 
 
    public ListviewAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 
    }
 
    public int getCount() {   //get the number of elements in the listview
        return data.size();
    }
 
    public Object getItem(int position) {   //this method returns on Object by position
        return position;
    }
 
    public long getItemId(int position) {   //get item id by position
        return position;
    }
 
    public View getView(int position, View convertView, ViewGroup parent) {   //getView method is the method which populates the listview with our personalized rows
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.listview_row, null);       //every item in listview uses xml "listview_row"'s design 
 
        TextView firstname = (TextView)vi.findViewById(R.id.tvFirstname);  //Here are two textviews in the listview_row xml file
        TextView lastname = (TextView)vi.findViewById(R.id.tvLastname);   // You can enter anything you want, buttons, radiobuttons, images, etc.
 
 
 
        HashMap<String, String> hash = new HashMap<String, String>();  //We need a HashMap to store our data for any item
        hash = data.get(position);
 
 
        firstname.setText(hash.get(Listview.KEY_FIRSTNAME));  //We personalize our row's items.
        lastname.setText(hash.get(Listview.KEY_LASTNAME));
 
 
        return vi;
    }
}

listview.xml :

<?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"
    android:orientation="vertical" >
 
    <ListView
        android:id="@+id/lvGenuine"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
 
</LinearLayout>

and finally listview_row.xml :

<?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"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/tvFirstname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Firstname"
        android:layout_marginLeft="20dip"
        android:textSize="25dip" />
 
    <TextView
        android:id="@+id/tvLastname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lastname"
        android:layout_marginLeft="40dip"
        android:textSize="15dip" />
 
</LinearLayout>

Here is a screenshot where you can see how it looks like :

You can download the entire project from here .

I hope you enjoyed the tutorial. I wait any kind of reviews and critics which I promise I will read and will think about them. If you’d like to see any tutorial for Android Development on www.androidgeniune.com you can leave a comment with your wish and I’ll try to help you.

This is all for now. Thank you for reading. See you !

 

||||| 0 I Like It! |||||

I will show you how to make a custom ListView.

Android Custom ListView and Custom ArrayAdapter

Create a new Android project in Eclipse with MainActivity as your default Activity and main.xml as your default layout file. Declare a ListView control in your main.xml layout file as shown in the following code.

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
 
<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
 
</LinearLayout>

The above code is using simple LinearLayout with vertical orientation, and a ListView is declared to cover the entire width and height of the parent container using the fill_parent as the value of both android:layout_height and android:layout:width properties. ListView also has a unique id listView1 that will be used in the MainActivity to reference the ListView control.

To create the custom header for the ListView, create a new xml layout file listview_header_row.xml in the layout folder of your project and declare a TextView control in it with the properties shown in the following code. This will create a blue header with the white color text showing Weather Photos.

listview_header_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
 
<TextView android:id="@+id/txtHeader"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#FFFFFF"
android:padding="10dp"
android:text="Weather Photos"
android:background="#336699" />
 
</LinearLayout>

To create a custom ListView row, create another xml layout file listview_item_row.xml in the project layout directory. Android will render this file content in every ListView item and you are free to declare any control you want in it. For this tutorial I am using an ImageView for an icon and a TextView for displaying items titles. Following is the code for listview_item_row.xml file.

listview_item_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
 
<strong><ImageView android:id="@+id/imgIcon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
 
<TextView android:id="@+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" /></strong>
 
</LinearLayout>

For this tutorial, I have downloaded some 32 x 32 pixels icons in PNG format. You can use your own icons if you want. Once your icons are ready, drag the icons from your folder to the project drawable-mdpi directory.

Next create a new Java class in your project and named it Weather.java. This class will be used to create a custom ArrayAdapter and to bind the objects with the ListView later in this tutorial. Following is the code of Weather.java class. It has two simple properties icon and title and a typical class constructor to initialize the properties.

Weather.java

public class Weather {
public int icon;
public String title;
public Weather(){
super();
}
 
public Weather(int icon, String title) {
super();
this.icon = icon;
this.title = title;
}
}

Notice that the above listview_item_row.xml file has two views, which are correspondent to the properties of the Weather class. The values of the Weather class properties will be displayed on those views and to connect these two pieces together you need to create a custom ArrayAdapter that will inherit the Android ArrayAdapter class and will override the getView method. Add a new java class in your project with the name WeatherAdapter and implement the code as shown below:

WeatherAdapter.java

public class WeatherAdapter extends ArrayAdapter&lt;Weather&gt;{
 
Context context;
int layoutResourceId;
Weather data[] = null;
 
public WeatherAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
 
<strong>@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
 
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
 
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
 
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
 
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
 
return row;
}</strong>
 
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}

In the above code, the first important thing is the constructor of the class that takes three parameters. The first parameter is the Context and we can pass the reference of the activity in which we will use WeatherAdapter class. The second parameter is the resource id of the layout file we want to use for displaying each ListView item. We will pass the resource id of our layout file listview_item_row.xml for this parameter. The third parameter is an array of Weather class objects that will be used by the Adapter to display data.

Next the parent class getView method is overridden. This method will be called for every item in the ListView to create views with their properties set as we want. The getView method is also using a temporary holder class declared inside the WeatherAdapter class. This class will be used to cache the ImageView and TextView so they can be reused for every row in the ListView and this will provide us a great performance improvement as we are recycling the same two views with different properties and we don’t need to find ImageView and TextView for every ListView item. The above code is also using the Android built in Layout Inflator to inflate (parse) the xml layout file.

The final piece of code is our application MainActivity in which we will be using all the above objects we declared. Following is the code of the MainActivity.java file.

MainActivity.java

public class MainActivity extends Activity {
 
private ListView listView1;
 
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
 
<strong>Weather weather_data[] = new Weather[]
{
new Weather(R.drawable.weather_cloudy, "Cloudy"),
new Weather(R.drawable.weather_showers, "Showers"),
new Weather(R.drawable.weather_snow, "Snow"),
new Weather(R.drawable.weather_storm, "Storm"),
new Weather(R.drawable.weather_sunny, "Sunny")
};
 
WeatherAdapter adapter = new WeatherAdapter(this,
R.layout.listview_item_row, weather_data);</strong>
 
 
listView1 = (ListView)findViewById(R.id.listView1);
 
<strong>View header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
 
listView1.setAdapter(adapter);</strong>
}

There are few things in the MainActivity that required explanation for your better understanding. First notice, we are creating an array of Weather class objects and icons and titles are passed as constructor parameters. Next, WeatherAdapter object is created and listview_item_row.xml layout file resource id and Weather objects array is passed in its constructor. Once again, we are using Android Layout Inflator to inflate our listview_header_row.xml layout file and once it is parses as header View it is passed as a parameter of ListView addHeaderView method. Finally we are passing our custom adapter to ListView setAdapter method. That’s about it. You are ready to build and run our project. If everything implemented properly you will see the following output.

Android Custom ListView and Custom ArrayAdapter
||||| 6 I Like It! |||||

Search

Popular

Sponsors