Wednesday, January 9, 2013

16 How to create custom Listview in Android

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.

In this tutorial, we show you how to create a custom list view with some images, texts... We want to make a list view to store information about a list of foobal legend, in particular each row has to contain: an image of the legend, the name, the date of birth and the image of his nationality.

Here is a result of this tutorial:

Android Custom ListView example

This project is developed in Eclipse 4.2.0.

1. Make application interface: The main layout of this app demo have one text view and one list view.


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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Foolball Legends"
        android:textColor="#008000"
        android:textSize="25dp"
        android:layout_margin="3dp"
        />
    <ListView
        android:id="@+id/FootballLegend_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingTop="5dp" >
    </ListView>
   
</LinearLayout>

Now is the time we customize our list view by create the layout for each row of it:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_selector"
    android:orientation="horizontal"
    android:padding="5dip" >

    <!--  ListRow Left side Thumbnail image -->
    <LinearLayout android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="3dip"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip">
        <ImageView
            android:id="@+id/legendImage"
            android:layout_width="50dip"
            android:layout_height="50dip" />
    </LinearLayout>
 
    <TextView
        android:id="@+id/legendName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Rihanna Love the way lie"
        android:textColor="#040404"
        android:typeface="sans"
        android:textSize="15dip"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/legendBorn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/legendName"
        android:textColor="#343434"
        android:textSize="10dip"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"  />
 
    <ImageView
        android:id="@+id/Nation"
        android:layout_width="45dp"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="5dp"
        android:layout_centerVertical="true" />

</RelativeLayout>
For android:background attribute of list view, we make res/drawable/list_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selector style for listrow -->
<item
 android:state_selected="false"
    android:state_pressed="false"
    android:drawable="@drawable/gradient_bg" />
<item android:state_pressed="true"
    android:drawable="@drawable/gradient_bg_hover" />
<item android:state_selected="true"
    android:state_pressed="false"
    android:drawable="@drawable/gradient_bg_hover" />
</selector>
And for all state of  list selector above we need two file below:
res/drawable/gradient_bg.xml for default background
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <!--  Gradient Bg for listrow -->
  <gradient
      android:startColor="#f1f1f2"
      android:centerColor="#e7e7e8"
      android:endColor="#cfcfcf"
      android:angle="270" />
</shape>

And For res/drawable/ gradient_bg_hover.xml for press state:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <!-- Gradient BgColor for listrow Selected -->
  <gradient
      android:startColor="#DA7648"
      android:centerColor="#DC6833"
      android:endColor="#C6724B"
      android:angle="270" />
</shape>

Thus we have completed the design of the interface. Now begin make some codes.

2. Code
2.1. We start by creating the FootballLegend’s object
package DucNguyen.example.customlistview;
public class FootballLegend {
        public FootballLegend(String name, String born, String image, String nation) {
                super();
                this.name = name;
                this.born = born;
                this.image = image;
                this.nation = nation;
        }
        private String name;
        private String born;
        private String image;
        private String nation;

        public String getName() {
                return name;
        }
        public void setName(String nameText) {
                name = nameText;
        }
        public String getNick() {
                return born;
        }
        public void setNick(String born) {
                this.born = born;
        }
        public String getImage() {
                return image;
        }
        public void setImage(String image) {
                this.image = image;
        }
                public String getNation() {
                return nation;
        }
        public void setNation(String image) {
                this.image = nation;
        }
}
2.2. Then create a custom adapter for the list viewFootballLegendListAdapter

package DucNguyen.example.customlistview;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class FootballLegendListAdapter extends ArrayAdapter<FootballLegend> {
        private int                             resource;
        private LayoutInflater  inflater;
        private Context                 context;
        public FootballLegendListAdapter ( Context ctx, int resourceId, List<FootballLegend> objects) {
                super( ctx, resourceId, objects );
                resource = resourceId;
                inflater = LayoutInflater.from( ctx );
                context=ctx;
        }
        @Override
        public View getView ( int position, View convertView, ViewGroup parent ) {
                convertView = ( RelativeLayout ) inflater.inflate( resource, null );
                FootballLegend Legend = getItem( position );
                                TextView legendName = (TextView) convertView.findViewById(R.id.legendName);
                legendName.setText(Legend.getName());
                 
                TextView legendBorn = (TextView) convertView.findViewById(R.id.legendBorn);
                legendBorn.setText(Legend.getNick());
                 
                ImageView legendImage = (ImageView) convertView.findViewById(R.id.legendImage);
                String uri = "drawable/" + Legend.getImage();
            int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
            Drawable image = context.getResources().getDrawable(imageResource);
            legendImage.setImageDrawable(image);
           
            ImageView NationImage = (ImageView) convertView.findViewById(R.id.Nation);
                uri = "drawable/" + Legend.getNation();
            imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
            image = context.getResources().getDrawable(imageResource);
            NationImage.setImageDrawable(image);

                return convertView;
        }
}

2.3. And finally, we set adapter for the list view with a array of FootballLegend's objects and setOnItemClickListener for this list view to show a Toast when click on any row on list.
package DucNguyen.example.customlistview;

import java.util.ArrayList;
import java.util.List;  
import android.os.Bundle;
import android.app.Activity;
import android.content.Context; 
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class CustomlistviewActivity extends Activity {
        private ListView listViewFootballLegend;
        private Context ctx;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customlistview);       
        ctx=this;      
        List<FootballLegend> legendList= new ArrayList<FootballLegend>();
        legendList.add(new FootballLegend("Pele","October 23, 1940 (age 72)","pele","brazil"));
        legendList.add(new FootballLegend("Diego Maradona","October 30, 1960 (age 52)","maradona","argentina"));
        legendList.add(new FootballLegend("Johan Cruyff","April 25, 1947 (age 65)","cruyff","netherlands"));
        legendList.add(new FootballLegend("Franz Beckenbauer","September 11, 1945 (age 67)","beckenbauer","germany"));
        legendList.add(new FootballLegend("Michel Platini","June 21, 1955 (age 57)","platini","france"));
        legendList.add(new FootballLegend("Ronaldo De Lima","September 22, 1976 (age 36)","ronaldo","brazil"));

        listViewFootballLegend = ( ListView ) findViewById( R.id.FootballLegend_list);
        listViewFootballLegend.setAdapter( new FootballLegendListAdapter(ctx, R.layout.legend_row_item, legendList ) );
   
        // Click event for single list row
        listViewFootballLegend.setOnItemClickListener(new OnItemClickListener() {
@Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FootballLegend o = (FootballLegend) parent.getItemAtPosition(position); 
                Toast.makeText(CustomlistviewActivity.this, o.getName().toString(), Toast.LENGTH_SHORT).show();
                }
        });            
    }
}

3.DEMO
3.1. Run application
Android Custom ListView example - Figure 2


3.2. Click on a row of list view

Android Custom ListView example - Figure 3


You can download all source codes of this tutorial from here.
Reference: http://www.androidhive.info



16 comments:

  1. In above when click print in toast but i want to open this file.can u give me suggestion

    ReplyDelete
  2. Thank you for this excellent tutorial, it has helped me a lot.
    I need to add a checkbox to the adapter but so far I have not succeeded.
    An help you can offer would be most welcome.

    ReplyDelete
  3. Thank you for useful article!

    ReplyDelete
  4. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    Java training in Bangalore | Java training in Electronic city

    Java training in Bangalore | Java training in Marathahalli

    Java training in Bangalore | Java training in Btm layout

    Java training in Bangalore | Java training in Jaya nagar

    ReplyDelete
  5. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    python training in chennai
    python training in chennai
    python training in bangalore

    ReplyDelete
  6. Excellent blog I visit this blog it's really awesome. The important thing is that in this blog content written clearly and understandable. The content of information is very informative. We are also providing the best services click on below links to visit our website.
    Oracle Fusion HCM Training
    Workday Training
    Okta Training
    Palo Alto Training
    Adobe Analytics Training

    ReplyDelete
  7. Great post. keep sharing such a worthy information.

    ReplyDelete