Home > Android > Working with ListView in Android. Customize ListView, Add item via a Button Click. And also clickable each button in each row

Working with ListView in Android. Customize ListView, Add item via a Button Click. And also clickable each button in each row

Hi all

How are you. Today I will describe about ListView in Android.
ListView is Very interesting control in Android. You can fully customize the ListView and can represent data as you need.

Eash list item is also be possible to customize  (Which will be rendered per list item).

OK. Now i will deliver you a sample ListView application

My Application screen shot is like below:

ListView Images

Figure 1: ListView Application

Description: A user will enter “Name” and “Mobile” number and when press click button, A item will be added in a ListView.

Please note, this is a in memory representation of data. I do not save this data to device. So runtime you can add item, after re running list will be empty.

Sources:

Sources files can be categorized into several parts

1. Layout

There are two layout files for this. One for Main Application UI,  Second for ListView Item representation

3. Java Sources

There are Three Java Classes for that. One for Main Activity (ListActivity), Second,for CustomAdapter, Third, A Model Class to represent Name and Email.

* Layout (main.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:gravity="center|top"
>

<Button
android:id=”@+id/ButtonToast”
android:text=”Toast MSG”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:width=”100px”
android:height=”20px”
android:layout_marginRight=”10px”
android:layout_marginTop=”5px”
>
</Button>

<Button
android:id=”@+id/ButtonDialog”
android:text=”Dialog MSG”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:width=”100px”
android:height=”20px”
android:layout_marginTop=”5px”
>
</Button>

</LinearLayout>

* Layout (list_item.xml)

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:id=”@+id/LinearLayout01″
android:paddingTop=”4dip”
android:paddingBottom=”6dip”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:orientation=”horizontal”>
<TextView
android:id=”@+id/lst_item_Name”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:minWidth=”120px”
>
</TextView>
<TextView
android:id=”@+id/lst_item_Mobile”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_marginLeft=”10px”
android:minWidth=”120px”
>
</TextView>
<Button
android:id=”@+id/lst_item_Delete”
android:text=”Delete”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:width=”80px”
>
</Button>
</LinearLayout>

* Java (ListActivity)

package com.blog.exercise;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.blog.exercise.Model.PersonalInfo;

public class ListActivity1 extends ListActivity {
/** Called when the activity is first created. */
ArrayList<PersonalInfo> newList = null;

SimpleAdapter adpt = null;

private Button btnSave = null;

private EditText txtName = null;
private EditText txtMobile = null;
private CustomListAdapter newAdpt = null;
private int i = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listlayout);
newList = new ArrayList<PersonalInfo>();

newAdpt = new CustomListAdapter(this, R.layout.list_item, newList);
setListAdapter(this.newAdpt);

txtName = (EditText)findViewById(R.id.txtName);
txtMobile = (EditText)findViewById(R.id.txtMobile);
btnSave = (Button)findViewById(R.id.btnSave);

btnSave.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
newList = new ArrayList<PersonalInfo>();
PersonalInfo info = new PersonalInfo();
info.SetName(txtName.getText().toString());
info.SetMobile(txtMobile.getText().toString());
newList.add(info);
//Thread.sleep(2000);

if(newList != null && newList.size() > 0){
newAdpt.notifyDataSetChanged();
newAdpt.add(newList.get(0));
i++;
// for(int i=0;i<newList.size();i++)
//     newAdpt.add(newList.get(i));
}

newAdpt.notifyDataSetChanged();

}
});
}
}

* Java (Custom List Adapter)

package com.blog.exercise;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.blog.exercise.Model.PersonalInfo;

public class CustomListAdapter extends ArrayAdapter<PersonalInfo> {
private Context appContext = null;
private ArrayList<PersonalInfo> items = null;
public CustomListAdapter(Context context, int textViewResourceId, ArrayList<PersonalInfo> items){
super(context,textViewResourceId,items);
this.appContext = context;
this.items=items;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
PersonalInfo o = items.get(position);
if (o != null) {
TextView name = (TextView) v.findViewById(R.id.lst_item_Name);
TextView mobile = (TextView) v.findViewById(R.id.lst_item_Mobile);
Button btnDelete = (Button)v.findViewById(R.id.lst_item_Delete);

btnDelete.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View view) {
Toast.makeText(appContext,”Hellow this is clicked”, Toast.LENGTH_LONG).show();

}
});

if (name != null) {
name.setText(o.GetName());                            }
if(mobile != null){
mobile.setText(o.GetMobile());
}
}
return v;
}
}

* Java (Model Class)

package com.blog.exercise.Model;

public class PersonalInfo {
private String name = “”;
private String mobile = “”;

public void SetName(String name){
this.name = name;
}
public String GetName(){
return this.name;
}

public void SetMobile(String mobile){
this.mobile = mobile;
}
public String GetMobile(){
return this.mobile;
}
}

This is IT. Enjoy

Categories: Android
  1. Birju Lodhiya
    April 27, 2012 at 10:35 am

    this code is pretty good handle Click event in listview is difficult task my personal experience.
    her you take ArrayAdapter but my point is that suppose
    we take SimpleCursorAdapter then is it possible to trace the
    Delete event ???
    i try to hard but not success.
    when click on Delete button then do nothing.

    i want that when i press the delete button that item will be deleted in database.
    i also want same thing for update

    two button are in each row Delete and Update
    when i click item will be deleted or update function will call according.

    if you have any valuable suggestion then kindly inform me
    as soon as because my project submission is near in two days.

    thanks brother!!!

  2. April 27, 2012 at 6:02 pm

    Hi Birju,

    Its very simple. Just see the CustomAdapter Class. Here I have a delete button event for each row. Just use this event to remove row in any collection (DB or other).

    For you, I am giving a sample here. Just see the 1, 2, and 3 section mentioned here

    public class CustomListAdapter extends ArrayAdapter {

    private Context appContext = null;
    private ArrayList items = null;

    public CustomListAdapter(Context context, int textViewResourceId,
    ArrayList items) {
    super(context, textViewResourceId, items);
    // TODO Auto-generated constructor stub
    this.appContext = context;
    this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    View v = convertView;
    if(v == null){
    LayoutInflater vi = (LayoutInflater)appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = vi.inflate(R.layout.list_item, null);
    }
    PersonalInfo o = items.get(position);

    if(o!= null){
    TextView name = (TextView)v.findViewById(R.id.list_item_name);
    TextView mobile = (TextView)v.findViewById(R.id.list_item_mobile);
    Button btnDelete = (Button)v.findViewById(R.id.list_item_Delete);

    //Section: 1. set tag for tracking row number in list
    btnDelete.setTag(position);

    //Section 2. click delete button listener
    //add code here to remove rows
    btnDelete.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    //Section 3. remove rows in list
    String pos = v.getTag().toString();
    int _position = Integer.parseInt(pos);
    items.remove(_position);
    notifyDataSetChanged();

    //just replace the 3
    //add a command to remove record from sqlite and
    //call notifyDataSetChanged(); thats all

    }
    });
    if(name != null)
    name.setText(o.GetName());
    if(mobile!=null)
    mobile.setText(o.GetMobile());
    }
    return v;

    }

    }

  3. d
    October 4, 2012 at 7:32 am

    hi dour codes work correctly?

  4. Mahesh Patel
    January 30, 2013 at 8:06 am

    where is your newAdpt.add() method?
    and what is its contain?
    newAdpt.add(newList.get(0));

  5. lihong
    January 31, 2013 at 3:38 am

    would you like to tell me how to save the item list to device?

  6. Eldar Tsafar
    February 12, 2013 at 5:56 pm

    I have a question about this code, if you can please contant me i need your help =] thanks in advance. my email is : eldartsa@gmail.com

  7. February 18, 2013 at 2:11 pm

    Hey I am so excited I found your website, I really found you by accident, while I was researching on Yahoo for something else, Anyways I am here now and would just like to say thank you for a incredible post and a all round
    thrilling blog (I also love the theme/design), I don’t have time to go through
    it all at the moment but I have saved it and also added in your RSS feeds, so when
    I have time I will be back to read a lot more, Please do
    keep up the excellent work.

  8. neal caffrey
    March 21, 2013 at 6:27 am

    hiiiiiiii,
    I want to create an app in which user can type country name in edit text & after clicking add button , country names should be displayed in Listview…So can you please send your entire code to my id : shankyfernandes@gmail.com

  9. Sreelal
    November 14, 2013 at 11:05 am

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.customlistview2/com.example.customlistview2.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is ‘android.R.id.list’

    What to do?

  10. u4fendo
    November 17, 2013 at 4:52 pm

    good work… thanks alot ^_^

  11. November 18, 2013 at 12:05 pm

    this code is not working Could 😦 don’t know why plz help
    arooj.saleem2011@gmail.com

  12. RENJITH
    March 9, 2014 at 6:56 am

    sir, i am new to android.
    where is your “listlayout” and this code does not contains any listview. i use this code but my app crashes when enter into ListActivity1 . please help me and also i dont understand the need of two buttons in main.xml..

  13. dikut andinata
    May 25, 2014 at 9:35 am

    can you send me the source code of this project? i so need the example like this project. i so grateful if you send me it.

  14. August 5, 2014 at 5:34 am

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android1/com.example.android1.MainActivity}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is ‘android.R.id.list’

    run time occured in my project? please give sollution sir?

  15. September 24, 2014 at 8:49 pm

    Hello, i think that i saw you visited my wweb site so i came to “return tthe
    favor”.I am attempting to find things to
    improve my site!I suppose its ok to use a few of your
    ideas!!

  16. December 19, 2014 at 8:47 am

    hi….i have one doubt i have list view with custom adapter custom row having two text views and one add button when i click on add button then get two text views and set to the another custom list view with two text views and one delete button like this example……..requirement is as same as your example ur taking two texts from edit text i want from list view

  1. March 10, 2013 at 7:23 am

Leave a comment