Android Custom Listview Tutorial - Part 2

Moving ahead from first part Custom List view,  we are going to discuss three things.

1.Adding background colors to Listview

2.Adding different Divider color.

3.Triggering action on listview click.

Step 1:

Listview Background Color

Adding Custom Background color to listview . For an elegance look for an application the listview color play a key role.

[sourcecode language="java"]

convertView.setBackgroundColor((position & 1) == 1 ? Color.WHITE : Color.LTGRAY);

[/sourcecode]

apply this snippet in the function getView();

customlistview backgroundcolor

Note:

You will lose item focus upon adding this background color.

Step 2 :

Adding divider color.

When you apply a white background to list cell. You need to have change the divider color since it gets hidden by the background color.

To change the background color

[sourcecode language="java"]

ColorDrawable divcolor = new ColorDrawable(Color.DKGRAY);
l1.setDivider(divcolor);
l1.setDividerHeight(2);

[/sourcecode]

customlistview dividercolor

Step 3:

Listview Click action

We have to use  OnItemClickListener to perform a action when an item on listview is clicked.

Upon clicking get the current position of the item on the listview then later its passed to the arraylist to get the country name that was clicked.

[sourcecode language="java"]

l1.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(), "You clciked "+country[arg2], Toast.LENGTH_LONG).show();

}

[/sourcecode]

customlistview onitemclicklistener -Androidpeople.com

Comments

Thanks Mineralwasser :) we

Thanks Mineralwasser :) we replaced it . Check it now.

Thanks :)

Thanks :)

hi tampiss, There is nothing

hi tampiss,

There is nothing to apologies for being newbie,

You have to create a instance for listview like in this example

http://www.androidpeople.com/android-custom-listv...

later after declaration you can insert this snippet