Android Snippet – Custom ListView with Image and Text

Android Snippet – Custom ListView with Image and Text

In this android code snippet, we are going to learn how to display an image and a text in a ListView items. The default use case of a ListView is to display a text in each List item.

If we want to customized the look and feel of our ListView in such a way that it can contain images and multiple text then we will build our own custom layout that will replace the default android layout for ListView items.

According to android user guide “ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that’s placed into the list”.

If you are interested in learning how to use a simple ListView with an ArrayAdapter, you can find it on the link above.

Before we start, the first thing I will do is to list the environment and tools I used in this android code snippet but feel free to use whatever environment or tools you are familiar with.

Windows 7

Android Studio

Samsung Galaxy Fame Lite

Min SDK 14

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: ListViewWithImageAndText

Package: com.inducesmile.listviewwithimageandtext

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

Once you are done with creating your project, make sure you change the package name if you did not use the same package.

Now that we are done with setting up our project, we will go further to create a new layout for our ListView.

Go to the res/layout folder and create a new layout file called listview_with_text_image.xml

Drag and drop a TextView and ImageView on the layout. We will use a Relative layout ViewGroup to wrap our View components. The listview_with_text_image.xml file will appear as shown below.

<?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:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/imageView"

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true"

android:layout_marginLeft="28dp"

android:layout_marginStart="28dp"

android:layout_marginTop="28dp" />

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="New Text"

android:id="@+id/textView"

android:layout_alignParentTop="true"

android:layout_toRightOf="@+id/imageView"

android:layout_toEndOf="@+id/imageView"

android:layout_marginTop="55dp"

android:textStyle="bold"

android:textSize="20dp"

android:layout_marginLeft="10dp"

android:layout_marginStart="32dp" />

</RelativeLayout>

Now we will move on to add to our main layout which will be contain a ListView. Open the activity_main.xml, in the design view of your IDE, drag and drop a ListView in the layout file. The xml code is shown below.

<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">

<ListView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/listView"

android:layout_alignParentTop="true"

android:layout_alignParentLeft="true"

android:layout_alignParentStart="true" />

</RelativeLayout>

We are going to create a class that uses the getter and setter methods to get and set the values of the image resource id and text. The code for the class is shown below.

package inducesmile.com.listviewwithimageandtext;

public class ItemObject {

private String name;

private int imageId;

public ItemObject(String name, int imageId) {

this.name = name;

this.imageId = imageId;

}

public int getImageId() {

return imageId;

}

public void setImageId(int imageId) {

this.imageId = imageId;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

Furthermore, we are going to create a custom adapter which we will use to inflate our custom layout for the list items. The getView method of the Adapter class was override and we used an inner class with is an instance of a ViewHolder to wrap our View components.

package inducesmile.com.listviewwithimageandtext;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.ImageView;

import android.widget.TextView;

import java.util.List;

public class CustomAdapter extends BaseAdapter {

private LayoutInflater lInflater;

private List<ItemObject> listStorage;

public CustomAdapter(Context context, List<ItemObject> customizedListView) {

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

listStorage = customizedListView;

}

@Override

public int getCount() {

return listStorage.size();

}

@Override

public Object getItem(int position) {

return position;

}

@Override

public long getItemId(int position) {

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder listViewHolder;

if(convertView == null){

listViewHolder = new ViewHolder();

convertView = lInflater.inflate(R.layout.listview_with_text_image, parent, false);

listViewHolder.textInListView = (TextView)convertView.findViewById(R.id.textView);

listViewHolder.imageInListView = (ImageView)convertView.findViewById(R.id.imageView);

convertView.setTag(listViewHolder);

}else{

listViewHolder = (ViewHolder)convertView.getTag();

}

listViewHolder.textInListView.setText(listStorage.get(position).getName());

listViewHolder.imageInListView.setImageResource(listStorage.get(position).getImageId());

return convertView;

}

static class ViewHolder{

TextView textInListView;

ImageView imageInListView;

}

}

The code in our MainActivity.java file is shown below.

So how did we achieve this?

1. In our MainActivity file, we obtained the instance of our ListView by calling the findViewById method of the activity class.

2. We created an instance of our custom Adapter with two parameters passed to it. The first one is the Application Context and a List that wraps objects of ItemObject class.

3. We set the object of our Adapter class as a parameter to setAdapter method of the ListView class

4. We attached an item click event. So whenever any item in the ListView is click, the position of the item will be displayed.

package inducesmile.com.listviewwithimageandtext;

import android.support.v7.app.ActionBarActivity;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.AdapterView;

import android.widget.ListView;

import android.widget.Toast;

import java.util.ArrayList;

import java.util.List;

public class MainActivity extends ActionBarActivity {

private ListView customListView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

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

List<ItemObject> listViewItems = new ArrayList<ItemObject>();

listViewItems.add(new ItemObject("Nigeria", R.drawable.imageone));

listViewItems.add(new ItemObject("Ghana", R.drawable.imagetwo));

listViewItems.add(new ItemObject("Senegal", R.drawable.imagethree));

listViewItems.add(new ItemObject("Togo", R.drawable.imagefour));

customListView.setAdapter(new CustomAdapter(this, listViewItems));

customListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

// make Toast when click

Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_LONG).show();

}

});

}

@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);

}

}

Save the file and run your project. If everything works for you, an image like this will appear on your test device.

android custom listview

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, kindly contact me.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published

No Responses

Add a Comment