So, here again, we start with extending ListActivity.
public class MyCustomListView extends ListActivity {
Now let us create the custom list view in an xml file – custom_list_view.xml. This will be set using the setContentView() in onCreate() method:
<ListView android:id="@id/android:list"Note that it must contain a ListView object with android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000fff"
android:layout_weight="2"
android:drawSelectorOnTop="false">
</ListView>
<TextView android:id="@id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFff00"
android:text="No data"
/>
I have also declared a TextView which should be whon when the list if empty by declaring with android:id="@id/android:empty"
Now we will declare how each row in this ListView should be displayed by creating a new xml file – custom_row_view.xml
I plan to have 3 items one below the other in each row. So, here is the declaration for the same:
<TextView android:id="@+id/text1"So, now, how do I tie all of this together? The MyCustomListView class, the listview layout and the row layout. Just like in the earlier example, we need a ListAdpater object. Here I plan to use a SimpleAdpater provided by the SDK.
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#FFFF00"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<TextView android:id="@+id/text2"
android:textSize="12sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="fill_parent"/>
<TextView android:id="@+id/text3"
android:typeface="sans"
android:textSize="14sp"
android:textStyle="italic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
An adapter expects the context, the layout and the handle to the data that needs to be displayed. So, let us create a list of data in an ArrayList of HashMaps. This way, the HashMap can store any amount of data.
static final ArrayList<HashMap<String,String>> list =This is just a declaration of the list object. We need to populate it with data. Our custom row layout expects each row to have 3 prices of data…
new ArrayList<HashMap<String,String>>();
This list is populated in a method as shown below with the 3 keys as ‘pen’, ‘price’ and ‘color’:
private void populateList() {
HashMap<String,String> temp = new HashMap<String,String>();So, now how do we tie up the data with the row layout and the listview layout. It is in this simple piece of code in the onCreate() method of MyCustomListView class:
temp.put("pen","MONT Blanc");
temp.put("price", "200.00$");
temp.put("color", "Silver, Grey, Black");
list.add(temp);
HashMap<String,String> temp1 = new HashMap<String,String>();
temp1.put("pen","Gucci");
temp1.put("price", "300.00$");
temp1.put("color", "Gold, Red");
list.add(temp1);
HashMap<String,String> temp2 = new HashMap<String,String>();
temp2.put("pen","Parker");
temp2.put("price", "400.00$");
temp2.put("color", "Gold, Blue");
list.add(temp2);
HashMap<String,String> temp3 = new HashMap<String,String>();
temp3.put("pen","Sailor");
temp3.put("price", "500.00$");
temp3.put("color", "Silver");
list.add(temp3);
HashMap<String,String> temp4 = new HashMap<String,String>();
temp4.put("pen","Porsche Design");
temp4.put("price", "600.00$");
temp4.put("color", "Silver, Grey, Red");
list.add(temp4);
}
setContentView(R.layout.custom_list_view);
SimpleAdapter adapter = new SimpleAdapter(
this,
list,
R.layout.custom_row_view,
new String[] {"pen","price","color"},
new int[] {R.id.text1,R.id.text2, R.id.text3}
);
populateList();Here we have set the default view to custom_list_view.
setListAdapter(adapter);
Then, using the SimpleAdapter, we have set the context, the list containing the data for display, the custom_row_view, the keys by which the data has to be fetched from the list, the TextViews into which the corresponding data has to be displayed.
Now execute and you will have a custom list view. Here is what you will get to see:
NOTE: if you do not populate the list with any data, you will see another view – the empty listview that we have defined in the custom_list_view.xml
You can download the complete source code for this example here.
Added later:
Based on a question below, I would like to add that an item can be clicked even in this custom list and the even captured by overriding the onListItemClick() method on the ListActivity class.
Here is the piece of code you can add to my sample, if you haev downlaoded and ti will toast a message on what has been selected:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String pen = o.toString();
Toast.makeText(this, "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show();
}
Enjoy....
Really your tutorial helps me lot....
ReplyDeleteCan you please post tutorial of using ActivityGroup.
hi,
ReplyDeleteDo u have any idea about dex cache.. SOme times (not all time) i am getting an some logs like this and my application fails.. Any idea what can be the reason ??
dalvikvm: Can't open dex cache '/data/dalvik-cache/system@app@myapp.apk@classes.dex': No such file or directory
04-11 02:26:37.345 1245 1245 I dalvikvm: Unable to open or create cache for /system/app/myapp.apk (/data/dalvik-cache/system@app@myapp.apk@classes.dex)
04-11 02:26:37.350 1245 1245 D AndroidRuntime: Shutting down VM
Jins
In my world, HashMap is a heave weight object. If there are many rows, this might become a prolem.
ReplyDeleteIs there any way to do this without using hash maps?
This comment has been removed by the author.
ReplyDeletehow to code to get its click event?
ReplyDeleteHi Khine,
ReplyDeleteYou just have to override the protected method on ListActivity - onListItemClick to capture the click event. I have added the same piece of code from the simple listview here.:
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String pen = o.toString();
Toast.makeText(this, "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show();
}
This should work for you.
Hi Anonymous,
ReplyDeleteRegarding the Hashmap being a heavy object, I agree. in my example, the data is hardcoded and hence I had to use hashmaps. However, in real applications, I would imagine that the data is coming from come content provider or SQLite DB and you could just iterate through the resultset and reuse a single collection object to populate the list. Just my thoughts... any other way you discover, feel free to share.
hi,
ReplyDeletethanks for your tutorial. I want to know, how to get value of listview set to onclicklistener, because in listview using position of array listview, not the value of listview itself. Thank you. Sorry for my english.
This comment has been removed by the author.
ReplyDeletei want a listview with icon as image with two line of text.how i ll do please help any one.
ReplyDeleteYour code worked like charm along with Toast, but i want to get the individual values of price and color, How do i do that? I am a newbie programmer in java
ReplyDeleteThanks in advance
how to create multi column ListView in gridview form in android?
ReplyDeleteI would be very thankful to u?
Hi Sai Geetha!
ReplyDeleteI have got a problem about event handler in my customized listview
My ListView have: ImageIcon, TextView and an ImageButton. As ListView14 example in API demos, i creat a classes extended BaseAdapter. In getView()
if(view == null) {
mHolder = new ViewHolder();
view = mInflater.inflate(R.layout.custom_list_item, null);
mHolder.song_icon = (ImageView) view.findViewById(R.id.music_icon);
mHolder.song_name = (TextView) view.findViewById(R.id.music_song_name);
mHolder.song_price = (TextView) view.findViewById(R.id.music_price);
mHolder.song_view = (TextView) view.findViewById(R.id.music_view);
//mHolder.play_btn = (ImageButton) view.findViewById(R.id.play_btn);
((ImageButton) view.findViewById(R.id.play_btn)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext , "Button Clicked: " +
mMusic.get(mPosition).name, Toast.LENGTH_LONG).show();
}
});
view.setTag(mHolder);
} else {
mHolder = (ViewHolder) view.getTag();
}
And now i want to handler event for each item(ImageView, TextView, and Button) by clicked on ImageButton an i want recervice text in TextView correlative with each ImageButton. Now, i have no idea to solve this problem. Please notify me when you have some ideas!
Thanks in advance!
Notify me via: khaintt@gmail.com
hi there. i loved this tuto. but i have a question. when we click on item appears a Toast text with {color=Silver, Price=500.00$, pen=Sailor}, but i want to appear just value of the tag pen without {}. how can i do this? thanks and waiting for your answer here or to my email lpedro1984@gmail.com .
ReplyDeleteanyone can help?
ReplyDeleteHi Luis,
ReplyDeleteThis is very simple Java code. When I convert the whole HashMap to String, it is showing with braces. Instead of converting the Object to String directly, convert it back to HashMap and retrieve the value for the key "pen".
Here is the code for the same:
HashMap fullObject = (HashMap)o;
Toast.makeText(this, "You have chosen the pen: " + " " + fullObject.get("pen"), Toast.LENGTH_LONG).show();
}
Thanks you so Sai Geetha.. Your posts are really great....!!!
DeleteSai Geetha you're the best! really... thanks.
ReplyDeleteHello, Thanks for the tutorial. I just had a question and may be you can help me out with that. Can I have the List View with a progress bar inside and not inherit my class from List Activity (I want the ListView to be scrollable part of my Linear Layout). Thanks and appreciate your feedback. Please reply so I can get a notification in my email.
ReplyDeleteReally your tutorial helps me for custum ListView but i need help Geeta where Custum ListView have icon image in the leftside and 3 line of text will display name,address and phonenumber .
ReplyDeleteHow would you change the typeface of text1 to a custom one ??
ReplyDeleteI think there must be a cheat inside your code, every time I put other Strings than yours into it stops working and shows just empty rows? (the right amount of rows, but empty ones) :X
ReplyDeleteI have to apologies, it was my fault, I screwed the workbench properties so awfully that it started making strange things with the R file .. so plz forget about my post above
ReplyDeletetipp for the rest of the readers: think first than post (or u r becoming blamed like me)
Hello Sai Geetha,
ReplyDeleteSimply u r d best.....
Regards,
Anji
Hi,
ReplyDeletePretty nice , informative and easy to follow tutorial.
And, hey can you help me with this one. I have a rowlayout in my custom adapter that has a button and two text views. How can I get the text of the button? I am currently using something like this: String btnText = ((Button)clickedView).getText();
It works fine. But, sometimes throws Android Runtime ClassCastException.
Kindly help!
Hi Sai Geetha,
ReplyDeleteI have a question.. can we select only one text view out of 3 text views you have added in each list item???
Ex: I want to select(click) only on "COLOR" textview out of "PEN" "COST" and "COLOR" from 1 listitem???
Hi Sai Geetha. I would like to ask how to edit the value of pen onItemClicked. Thanks
ReplyDeletehttp://mfarhan133.wordpress.com/2010/10/14/list-view-tutorial-for-android/
ReplyDeleteThis a simple android list view tutorial, you can also apply onClick listener,, complete source code is available
http://mfarhan133.wordpress.com/2010/10/14/list-view-tutorial-for-android/
ReplyDeleteThis a simple android list view tutorial, you can also apply onClick listener,, complete source code is available
Great tutorial!
ReplyDeleteI was able to modify it for my use but I am trying to also add an image from a url to the listview how would I do that?
I already added the image url to the array I just cant render it.
Respected Sai Geetha mam
ReplyDeletei want a listview with imageview,Imagebutton & 3 textview.
How can i use hashmap? how can i put image view & button in hashmap.
Plz reply as soon as possible
Respected Sai Geetha mam
ReplyDeletei want a listview with imageview,Imagebutton & 3 textview.
How can i use hashmap? how can i put image view & button in hashmap.
Plz reply as soon as possible
Hi,
ReplyDeleteI am not able to see color and price only pen value is displaying in the list.
Plz help me.
Hi,
ReplyDeleteIts really good. But why its displaying the repeated values in listview. It should display only once right..?
Hi,
ReplyDeletemeans every time by opening the app the values are increasing and repeating in listview. What may be the reason..
Hi Abhilash,
ReplyDeleteThe list if getting repopulated each time onCreate() is called. I have not written anything on the onDestroy() and onStop() Methods to ensure I clear the list before the app is closed.
That is the reason for the behaviour you are observing.
Hi Sai Geetha,
ReplyDeleteThanks for the reply. But in your previous example i.e basic example on listview, in it's not happening as happening in custom listview i.e repopulating the list. What may be the reason?
Hi,
ReplyDeleteI got the solution, just i removed static keyword in the below statement,
static final ArrayList> list =
new ArrayList>();
After removing the static keyword,the list not repopulating.
Very impressive tutorial. I liked it so much because it was so easy to understand and it worked the way it was described. I hope to see more tutorial like this around.
ReplyDeleteThanks for the help!
the above source code shows a list of items in a single line . can you suggest like this
ReplyDeletepen /n
price /n
cost /n
Really Really Helped me, I learned very easily and quickly..... Thanks a lot... Thats really great of you :)
ReplyDeleteVery nice.........
ReplyDeletehttp://www.wirelessrouterproxy.blogspot.com
Hi Mam, I need to create a customListview which contain Image , Name and a delete button.
ReplyDeleteAll the three should appear horizontally like,
--------------------------------------------
Image Name Deletebutton
--------------------------------------------
how this can be done, can you please help on this.
Thanks,
Jay
Hi mam,
ReplyDeleteyour all posts are really awesome.. thanks for such nice examples..
i wanted to know can we make listview with different headers to show different kind of data..
like names:
places:
events:
...
Really Helpful.But I want add Button on each List Item . Who Can I do?
ReplyDeletethanks, very helpful.. :D
ReplyDeleteDear Mam
ReplyDeletehow i display contact person photo in custom list view.
tell me how i refresh my listview(UI) when i get new message through broadcastReceiver. i update myArrayAdpater with notificationDataChanged But no change found on listview so plz. give useful solution
This comment has been removed by the author.
ReplyDeleteHi Sai Geetha...
ReplyDeleteThis is really educative blog.
I am fresher to android.
i have one question for you:
what modification should i do if i want a new window( new view) to show up, upon clicking any of the list items.
i found for buttons but what in the case of text within the list.
please help me in this.
please help me for this.
Hi,
ReplyDeleteI have to create a list view to display all the values of the hashmap to display the values retrieved from the database. In your example to create CustomListView you have hard coded the hashmap values. can you suggest me a way to create a array of hashmap
Here is something which i've tried
private void populateList() {
HashMap temp = new HashMap();
for(int j=0;j<name1.length;j++)
{
temp.put("name",name1[j]);
temp.put("tel", telephone1[j]);
list.add(temp);
}
}
Thanks a lot for the good tutorial
ReplyDeletevery very very very awesome...!!!! Thanks Alot
ReplyDeletefurther can you please make a tutorial for ListView with Images also...
ReplyDeleteSomething like lazy list...
But in simple way just like the above...!!!
Thanks alot in advance.
Awais
Thanks a lot
ReplyDeleteI tried & worked fine;
How do we add image into custom_row_view
ReplyDeletei dont know how to thankfull to i am...
ReplyDeletethanks a lot..
ReplyDeletethis very helpful for me.
Simple and beautiful tutorial thank you :)
ReplyDeleteYou have beautiful mind. Thanks a lot.
ReplyDeletethanks for all tuts,
ReplyDeletebut for this i add some other data in it but only 5 items are displaying suggest me solution.
thanks.
thanks for it,it helps me a lot..
ReplyDeletehi, could you help, please? :]
ReplyDeleteDo you remember what happen when there are a listview that contains some icons (about three icons), and I touch the screen and scrollup or scrolldown, so the list (of icons) moves and following my finger.
So I remove my finger from screen and the list back to the original position (because have less icon then the size of screen). Look this effect.
Well, my problem is that I have a activity and in this activity I've a View (HorizontalScrollView) and it don't have the same effect, like Listview. The icons (or other views) inside HorizontalScrollView just follows to touch event, but when it leaves the icons(views) stay at the position where it stopped.
As I don't find a horizontal listview, I'm trying to use scrollview with this effect. Do you know how to do this?
Thanks for your attention
great work done mam...your tutorials are always very helpful
ReplyDeleteHi,
ReplyDeleteI was wondering how to get the listview to differentiate between a long click and a regular click? I noticed there was no onLongListItemClick method in the ListActivity class.
Thanks!
how to make a list as a default list and i want to insert a button in the list view,how do we do this.ur blog is helping me a lot .please help me in this issue
ReplyDeletehi, i am rajeshkumar, new to android i want tutorials(with best example) for android..
ReplyDeleteThank You..
Hi, I am Padmanabhan. I use Listview in an activity and inflate with button.How i get the Button click event of button within the listview.
ReplyDeleteHai mam, i am fresher to android field..i am doing the program using listactivity..In this program i have the list and textview.the textview is used to display the heading for the list..but the textview is repeated for every item.pls clarify my doubt mam.Thanks in advance
ReplyDeleteIs there a way to not extend the ListActivity class and still use listview? I still want to extend Activity class. I'm kinda new to Android.
ReplyDelete+1 for last comment! Having issues trying to have a dynamic list view without ListActivity.
ReplyDeleteFigured it out! Here ya go:
ReplyDeletehttps://gist.github.com/1256137
hi
ReplyDeletei need to add row dynamically to multicolumn listview. can u pls guide me?
hi, I wantthe code for empty listview with three columns with the heading of names,phnos,favourites in XML,java in android...please help me its urgent looking for u r code
ReplyDeleteHai mam
ReplyDeleteIn my listview values are repeating.I am using sqlite database.please help me.it will be useful for my application
protected void onListItemClick (ListView l, View v, int position, long id){
ReplyDeletesuper.onListItemClick(l, v, position, id);
setContentView(R.layout.mylayout);
}
I want that instead of Toast to get a new layout with a textview, I have tried the code below but I get some truble about "mylayout".
@Mamatha, implement onDestroy() method
ReplyDelete@Override
public void onDestroy(){
super.onDestroy();
list.removeAll(list);
}
Hi..
ReplyDeleteI am creating customized list with multiple selection with help of Checkbox. At last i managed to set checkbox selected on list's item selection's event.
but when I check boxes are not being selected according to list's selection When I click on first row 4th row's check box gets clicked automatically . In short sequence is not maintained. The code with I am working is as below
ListAdapter adapter = new SimpleAdapter(
this,
Datalist ,
R.layout.customlist,
new String[] {"fileName","contentLength","keyPath"},
new int[] {R.id.title,R.id.size, R.id.path}
);
setListAdapter(adapter);
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ViewGroup group=(ViewGroup)v;
CheckBox check=(CheckBox)group.findViewById(R.id.sharecheckbox);
check.toggle();
}
How can i add a button to a list view using hashmaps?
ReplyDeleteThanks for this great tutorial .Now I have a problem in which i have to view image from url and display it in listview .So please suggest me how to solve this problem .
ReplyDeleteYou can send me on id androiddilip78@gmail.com
Thanks
Nice tutorial.
ReplyDeleteI need to implement an "OnListItemClick()" which can change the text-size of ListItem and row-size.
Any recommended way ?
Thanks dude..!!! This tutorial helped me to over come lots of difficulties on list view in Android.. Best Regards...!!!
ReplyDeletethanks!
ReplyDeleteThanks! I'd spent hours trying to figure this out, and your tutorial worked the first time! :)
ReplyDeleteplease see the question and help me.
ReplyDeletehttp://stackoverflow.com/questions/8544418/how-to-show-arrayadapters-text-and-icon-in-list-in-android
Is there any way to do with out using hashmap.
ReplyDeleteIf i get the 1000 values from databases then i need to create 1000 hashmaps with this code.
Is there any simple way to do it.
Thanks
Hi geetha
ReplyDeleteI am naresh. i want to develop an application like mobile backup.
in this one thing i thought is ""when ever i send a msg from another mobile with a keyword then the missed mobile has to swithoff whenever the msg is opened"" is it possible or not in android???
This is AWESOME! Thank you so much for this.
ReplyDeleteThank you very much for this short and very very helpfull example!!!!!!!!!
ReplyDeleteThis is one of the amazing post.I like your blog advantages.This is one of the nice post.Thanks for share with us.
ReplyDeleteThanks for sharing, I will bookmark and be back again
ReplyDeleteAndroid Developer
wonderful post., thank you...
ReplyDelete