» ListView with Sections_Separators
Transcript of » ListView with Sections_Separators
-
8/14/2019 ListView with Sections_Separators
1/13
Home
Projects
Tutorials
About
bartinger.at
stop(); //Hammertime
Type your search here...
Featured Post
Tutorial: Local game scores with SQLite
Create a standard Android-Project, or include the following into your game. At first we need a class which creates a database
it doesnt exist and can access the database. Make a new class and call it ScoreDatabase and extend it
from SQLiteOpenHelper import android.content.Context; import...
ReadMore
ListView with Sections/Separators
Posted by Bartinger | Posted in Al l, Tutorials| Pos ted on 11-07-2011
Tags: android, item, list, listview, section, separator, tutorial
65
Edit : ListView tutorial part 2 is about clickable widgets in ListView items Take a look!
http://bartinger.at/wp-content/uploads/2011/07/device-2011-07-11-171806.pnghttp://bartinger.at/wp-content/uploads/2011/07/device-2011-07-11-171806.pnghttp://bartinger.at/wp-content/uploads/2011/07/device-2011-07-11-171806.pnghttp://twitter.com/devbartingerhttp://twitter.com/devbartingerhttp://twitter.com/devbartingerhttp://twitter.com/devbartingerhttp://bartinger.at/http://bartinger.at/about/http://bartinger.at/category/projects/http://bartinger.at/clickable-widgets-in-listviews/http://bartinger.at/wp-content/uploads/2011/07/device-2011-07-11-171806.pnghttp://bartinger.at/tag/tutorial/http://bartinger.at/tag/separator/http://bartinger.at/tag/section/http://bartinger.at/tag/listview/http://bartinger.at/tag/list/http://bartinger.at/tag/item/http://bartinger.at/tag/android/http://bartinger.at/category/tutorials/http://bartinger.at/category/uncategorized/http://bartinger.at/listview-with-sectionsseparators/http://twitter.com/devbartingerhttp://bartinger.at/tutorial-locale-game-scores-with-a-sql-database/http://bartinger.at/tutorial-locale-game-scores-with-a-sql-database/http://bartinger.at/http://bartinger.at/about/http://bartinger.at/category/tutorials/http://bartinger.at/category/projects/http://bartinger.at/ -
8/14/2019 ListView with Sections_Separators
2/13
If youve ever used ListView, and i bet you had, then you will have noticed that it is not very handy if you want to display a
huge amount of data. I found a few solutions, how to categorize list items like in your phones preferences. This post wont be
about how it looks rather more about how to write it. Ill show you 2 solutions and describe one if it more detailed. There is no
perfect solution, but you can decide which one you prefer.
Solution #1:
One is to include the Sectionview in every item of your list and set its visibility to GONE. Then make it vis ible in each first
item. I dont like this one, because then you have a lot of unused TextViews (or whatever) which consumes memory. If youwant to read much more about ListView and sectioning, Cyril wrote a great postabout it. And here is my preferred way for
sectioning list items.
Solution #2:
I didnt like the first version so i thought about my own way to do it. (Before Cyrils post was written ). So what did I do? I
created 2 xml files. One for the section and one for the list item. If you want to have your section item look like that one in the
preferences you can get its attributes like that:
Of course you can design your section header however you want. The second xml is for all the list items. I copied it from
another project of mine, you can use it if you want.
-
8/14/2019 ListView with Sections_Separators
3/13
android:ellipsize="marquee"
android:fadingEdge="horizontal"/>
You can see how these layouts look like on the screenshot above. Next step is the javacode. I created 3 classes and one
interface.
EntryAdapter (ArrayAdapter)
Interface: Item
SectionItem (implements Item)
EntryItem (implements Item)
The Item interface contains the method:isSection();
This will return true when its a SectionItem and return false when its
EntryItem so that we can keep the two apart. Item, EntryItem and SectionItem arent that hard to understand, because there
isnt really much code. There are included in the project zip file at the end of the post. The Adapter should be a explained in
more detail. Heres the code:
publicclassEntryAdapterextendsArrayAdapter{
privateContextcontext;
privateArrayListitems;
privateLayoutInflatervi;
publicEntryAdapter(Contextcontext,ArrayListitems){
super(context,0,items);
this.context =context;
this.items =items;
vi =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
Viewv =convertView;
finalItemi =items.get(position);
if(i !=null){
if(i.isSection()){
SectionItemsi =(SectionItem)i;
v =vi.inflate(R.layout.list_item_section,null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
finalTextViewsectionView =
(TextView)v.findViewById(R.id.list_item_section_text);
sectionView.setText(si.getTitle());
}else{
EntryItemei =(EntryItem)i;
v =vi.inflate(R.layout.list_item_entry,null);
finalTextViewtitle =
(TextView)v.findViewById(R.id.list_item_entry_title);
finalTextViewsubtitle =
(TextView)v.findViewById(R.id.list_item_entry_summary);
if(title !=null)title.setText(ei.title);
-
8/14/2019 ListView with Sections_Separators
4/13
if(subtitle !=null)subtitle.setText(ei.subtitle);
}
}
returnv;
}
}
The interesting part is the getView() method. Here you have to keep the two apart and inflate either the section xml or the entr
xml. Cast the item, then inflate the right xml to get the view. Setup the TextViews or whatever you use in your items and then
return the view. Now how to actually add items in your activity (I use ListActivity for this example):
ArrayListitems =newArrayList();
items.add(newSectionItem("Category 1"));
items.add(newEntryItem("Item 1","This is item 1.1"));
items.add(newEntryItem("Item 2","This is item 1.2"));
items.add(newEntryItem("Item 3","This is item 1.3"));
items.add(newSectionItem("Category 2"));
items.add(newEntryItem("Item 4","This is item 2.1"));
items.add(newEntryItem("Item 5","This is item 2.2"));
items.add(newEntryItem("Item 6","This is item 2.3"));
items.add(newEntryItem("Item 7","This is item 2.4"));
EntryAdapteradapter =newEntryAdapter(this,items);
setListAdapter(adapter);
Pretty simple huh? Theres just one thing that you have to take care of. In the onListItemClick() method (and long click as
well of course) you have to check if the clicked item isnt a Section item.
if(!items.get(position).isSection()){
EntryItemitem =(EntryItem)items.get(position);
Toast.makeText(this,"You clicked "+item.title ,Toast.LENGTH_SHORT).show();
}
Thats all. Its definitely not the best solution, but I thinks its kinda handy and easy to understand. I tested it with 2000 items
and had no problem running it on the emulator and on my device. The full example can be downloaded
here. SectionListExample (6837)If you have any questions feel free to leave a comment and Ill reply as soon as possible. Sohave a nice day.
Subscribe to this blog
64 comments
Leave a message...
Best Community Share
Amjat h
good post. really useful for me to implement categorized list view
4
1
Avatar
http://fusion.google.com/add?source=atgs&feedurl=http%3A//bartinger.at/feedhttp://fusion.google.com/add?source=atgs&feedurl=http%3A//bartinger.at/feedhttp://bartinger.at/wp-content/plugins/download-monitor/download.php?id=3 -
8/14/2019 ListView with Sections_Separators
5/13
sunil
how to add the search item in this list view. Please help me thanks
1
Dominic Bartl M od
What do you mean by search item?
If I understood you correctly, what you could do is create a layout xml with an EditText, add
isSearchItem();
in the Item interface and create a new class SearchItem which also implements the Iteminterface.
sunil
can you please add same functionality and mail me at [email protected] thank
upile
Hi Great tutorial, im new to android development and was wondering how you would make the code not
repeat the category if it already exists, thanks
1
Bhupendra
how to categorized the expandable listview like same u did for listview
1
tote
ok i was able to correct my code by removing i check in the getView event. The code I had was checkin
to see if convertView had already been inflated and set to something and if it had to just return it as is. I
removed the check and now just have it inflate a new view for each row all the time and I get the data I
want, but the scrolling seems to lag a little bit.
1
Dominic Bartl M od
Yes, sorry that I couldn't reply. I had the some problem once and did the same mistake.
Raven3221
What about View Holder pattern?
You're not reusing the views that were already created.
Solution 1 can use this pattern and save a lot of inflating.
1
Dominic Bartl M od
I know. I already created a list with a holder. I'll put up another tutorial with this pattern soon.
Avatar
Avatar
Avatar
Avatar
Avatar
http://disqus.com/disqus_9DNfrfI3vo/http://disqus.com/disqus_9DNfrfI3vo/http://disqus.com/disqus_9DNfrfI3vo/http://disqus.com/Bartinger/http://disqus.com/Bartinger/http://disqus.com/disqus_9DNfrfI3vo/http://disqus.com/Bartinger/http://disqus.com/disqus_9DNfrfI3vo/ -
8/14/2019 ListView with Sections_Separators
6/13
dhara
Thanks for the post
1
Brandon Ulasiewicz
This is a great resource. Thanks for the post :-)
I have a quick question about this ... is there a way to have a static background image to be placed
behind everything so that when you you scroll the image will stay put and the list will scroll?
1
Dominic Bartl M od
Sorry I forgot to answer to your comment. What you can try is to create a layout via xml with a
LinearLayout and a ListView in it. Set the background image to the LinearLayout and make the
background of the list items transparent.
kdawg
Great post. Will this implementation support fast scrolling? In particular, what would be great is to hav
fast scrolling where only the "section items" appear in the zoomed view. I am a bit new to this and wou
appreciate your thoughts.
1
Dominic Bartl M od
Just call:
getListView().setFastScrollEnabled(true);and you will have the drag-able Image on the right.
I'll have a look on it with the SectionItems.
Maybe I'll make an Part 2 of this Tutorial with fastscrolling
1
Mamil
exactly what im looking for thaks
1
Rahul
If i want to remove element..then how that can be done.......
James
awesome..but how to remove a row using this approach?
Miguel Angel Jimenez Sanchez
Avatar
Avatar
Avatar
Avatar
Avatar
Avatar
Avatar
http://disqus.com/google-4220545cc6005f6fef6227a9606bab1b/http://disqus.com/Bartinger/http://disqus.com/Bartinger/http://disqus.com/google-e98b1e43281aceaba98294923861671d/http://www.theultimateandroidlibrary.com/ -
8/14/2019 ListView with Sections_Separators
7/13
, . ...
hongken
I really appreciate it. You saved me !!!
Oli Viner
Great tutorial. I have been parsing a JSON with items and sub-items and this has worked a treat, excep
for one major issue - the SectionItems are appearing in a random order?! The entries are associated
with the correct sections but the sections are all over the place. When I check the JSON or parse it usin
an expandable listview (which I do not want as it is very slow and I want the groups permanently
expanded) they are in the correct order. Any ideas why this may be happening?
Steph68
Hi!
First, congrats for that sectionned listview, very nice! :-D
I am just wondering how could it be possible to include a footer within?
Could you maybe help? ;-)
Thanks.
Steph68
Sorry for multiple posts.
I expected to see my question sorted by date, on the top of the list, so I meant it didn't worked...
Steph
Hi!
First, congrats for that sectionned listview, very nice! :-D
I am just wondering how could it be possible to include a footer within?
Could you maybe help? ;-)
Thanks.
Steph
Hi!
First, congrats for that sectionned listview, very nice! :-D
I am just wondering how could it be possible to include a footer within?
Avatar
Avatar
Avatar
Avatar
Avatar
http://disqus.com/Steph68/http://disqus.com/Steph68/http://disqus.com/google-fd07eb62e33873a4c6b1597b99359ae4/http://disqus.com/google-4220545cc6005f6fef6227a9606bab1b/http://www.theultimateandroidlibrary.com/ -
8/14/2019 ListView with Sections_Separators
8/13
Could you maybe help? ;-)
Thanks.
Ivan
This is a very useful tutorial. I need a longest Listview so ill add more items and done. I have a question
I would also like to have an image on each section (but different in each one) as
there is
only a list_item_section, how can I do it? Thanks in advance and congrats again for the tutorial
Dominic Bartl M od
So what you want is a different image in each section-item?
Ivan
Yes, would it be possible?
Dominic Bartl M od
If you want a background image just add an id to the LinearLayout in the section
xml-file and set the background image in your code.
Or you just add an ImageView and set the image in code, but I'm not quite sure if
that works.
You have to edit the section xml-file though.
ivan
Im really lost Bartinger, im sorry. I have to modify list_item_section.xml I though
it was easier by adding an ImageView but I dont know how to set the image
because it would be different in every section and if I add a background image in
LinearLayout I dont know how to add the different image in each section. Thanks
again my friend
Dominic Bartl M od
In the SectionItem class add a new field
private final int drawableID;
You need to update the constructor and add getters as well. In the getView metho
if the item is a SectionItem you just get your ImageView exactly like the TextView
and with
imageView.setImageResource(si.getDrawableId());
you can set the Image
Avatar
http://disqus.com/Bartinger/http://disqus.com/Bartinger/http://disqus.com/Bartinger/ -
8/14/2019 ListView with Sections_Separators
9/13
Ivan
I dis as you said, this is SectionItem:
private final String title; private final int drawableID; public SectionItem(String title,
int drawableID) { this.title = title; this.drawableID = drawableID; } public String
getTitle(){ return title; } public boolean isSection() { return true; }
public int getDrawableID() { return drawableID; }
with private final int drawableID; and public int getDrawableID().
Then I add in EntryAdapter
final ImageView imageView = (ImageView)
v.findViewById(R.id.list_item_entry_drawable);imageView.setImageResource(si.g
And now to add the image in the main activityitems.add(new
SectionItem("Euromillones", R.drawable.circulo_blanco)); and the app doesnt. D
I need to add an ImageView in list_item_section.xml before the include?
Thanks again to be so patient
Ivan
and if so, how can I do it??
ud i
thank you very much
Allene
Great Post. It Helped me a Lot in creating section list view.
I have a created a listview with your code, with a little modification to the xml file. i removed one textview
and inserted edittext view in the xml file. now i want to get the value from the edittext view form each item
and store it in respective variables for further calculation. problem is i can't get the value through
findViewById, because i have only one ID for edittext view. i have no idea how to solve this problem.
Dominic Bartl M od
I wouldn't even put a EditText into a ListView. What I would do is to pop up a dialog with an
EditText and then let the user make his input there. However if you really want to have it in your
ListView you could store the EditText in the EntryItem and when you click on it you read the valu
tote
@Bartinger : Helpful post, for sure. I'm having problems applying it when I have many items in my list
where the user has to scroll through the items.It seems that only the items in view are retrieved through
get view. So at first my list and headers look fine. Once I start scrolling down past what was initially
Avatar
Avatar
Avatar
http://disqus.com/Bartinger/ -
8/14/2019 ListView with Sections_Separators
10/13
v s e, or some reason get repeats o ea ers t at s ou not e t ere. y tems array st oo s ne
structurally. I have a section i position 1. 1 item under that section. Then another section. Then 27 more
items for that section. But when I start scrolling things get messed, and I get duplicate sections with
items that belong to another section etc.... anyone see anything like this?
Johnnie Hammonds
First off, I want to say thanks for the post. You've done a really nice job with it. I also thought I would
mention that I extended your work a bit to make the Activity generic. This allows me to use the same se
of classes for any number of custom lists that I want.
To do this, all I had to do was pass in the ArrayList via the intent when starting the activity (using
startActivityForResult), then return the selected item as a result when exiting the activity.
Thanks again!
Dominic Bartl M od
glad i could help!
Usha Keesara
in this program where is the main.xml calling
Padman009
Hello there,the code is excellent but how can I use different icons for the list items?
Yusuf Wagh
Great Example Helped me a lot but i had an Issue i have used your structure my listview row contains
images which are coming from server and when i scroll it again n again it gets crashed and memory
warning is issued .. because layout is getting inflated every time
apache
Yes :) After one year I discovered it. How did you menaged it?
For me putting
if (v==null){
...
}
in getview
kinda solved problem
Avatar
Avatar
Avatar
Avatar
http://disqus.com/Bartinger/http://disqus.com/google-493b1e4e9325be88282d97bc2b98610e/ -
8/14/2019 ListView with Sections_Separators
11/13
Amit Moh ite27
nice post, very helpful
Mahesh Chunkhade
hello..it is really very good tutorial for section list view..
it help me lot to understand how to construct section list view
thanks
_x enix
Hello, good post. I want explication under the question "I have a quick question about this ... is there a
way to have a static
background image to be placed behind everything so that when you you
scroll the image will stay put and the list will scroll?" i not understand how do you do... Thanks
Damiano Corrado
Thank you
DroidRookie
That helps Bartinger.
A simple and effective piece of code which never flashed in my brain
Markus Weller
Is there anything I have have to take care of if this is not my main Activity?
I have writen a XML File with a list in it and have a setContentView to this View.But nothing is displayed,
my list remains empty and the getView Methode is never used.
Dominic Bartl M od
Hey Markus.
If you're using a normal Activity instead of a ListActivity like me and added the ListView via the
XML layout, you have to change this line: "setListAdapter(...)" to something like this...
ListView listView = (ListView) findViewById(R.id.your_listview);
listView.setAdapter(adapter);
Did you do that ?
Avatar
Avatar
Avatar
Avatar
Avatar
Avatar
http://disqus.com/Bartinger/http://disqus.com/twitter-70482366/http://disqus.com/facebook-1628649395/http://disqus.com/google-74e01c15964f26d6135ffb4477c8b49b/ -
8/14/2019 ListView with Sections_Separators
12/13
Load more comments
About
I'm 20 years old, currently working as a freelance web and Android developer, interested in a wide-
range of technology topics, including programming languages, data storage, opensource and any other cool technology
that catches my eye. I love developing apps for Android, designing and coding websites.
Follow me
Google
Tags
3gandroidblackberryblogbluetoothbrightnessclockworkmodflashfreegameguidehowtoitemjavalglg2xlist
http://bartinger.at/tag/list/http://bartinger.at/tag/lg2x/http://bartinger.at/tag/lg/http://bartinger.at/tag/java/http://bartinger.at/tag/item/http://bartinger.at/tag/howto/http://bartinger.at/tag/guide/http://bartinger.at/tag/game/http://bartinger.at/tag/free/http://bartinger.at/tag/flash/http://bartinger.at/tag/clockworkmod/http://bartinger.at/tag/brightness/http://bartinger.at/tag/bluetooth/http://bartinger.at/tag/blog/http://bartinger.at/tag/blackberry/http://bartinger.at/tag/android/http://bartinger.at/tag/3g/https://plus.google.com/104044628968887313741?rel=authorhttp://twitter.com/#!/DevBartingerhttp://partners.webmasterplan.com/click.asp?ref=584411&site=8170&type=b8&bnb=8https://disqus.com/admin/signup/?utm_source=bartingerat&utm_medium=Disqus-Footerhttp://disqus.com/ -
8/14/2019 ListView with Sections_Separators
13/13
listviewmarketminecraftmodaconvflashoptimusorganisationpatternplaybookprogramming languagerescueringermoderom
rootscoresectionseparatorsettingssmartphoneSmart Phonesoftwaresqlsublimetegratipstutorialvolumewifi
Links
Alexander Ott
Grub2 Basics
Me on Twitter
Mobile Tuts+
Smart GWT
Smart Phone
ThomasJirout
TomTasche
bartinger.at
All Rights Reserved. bartinger.at| Powered by : WordPress
Designed by : WebDesignLessons.com
http://www.webdesignlessons.com/http://wordpress.org/http://bartinger.at/http://bartinger.at/http://tomtasche.at/http://tomweb.at/http://smartphone.bartinger.at/http://www.smartclient.com/smartgwtee/showcase/#mainhttp://mobile.tutsplus.com/http://twitter.com/#!/DevBartingerhttp://ubuntuforums.org/showthread.php?t=1195275http://alexanderott.at/http://bartinger.at/tag/wifi/http://bartinger.at/tag/volume/http://bartinger.at/tag/tutorial/http://bartinger.at/tag/tips/http://bartinger.at/tag/tegra/http://bartinger.at/tag/sublime/http://bartinger.at/tag/sql/http://bartinger.at/tag/software/http://bartinger.at/tag/smart-phone/http://bartinger.at/tag/smartphone/http://bartinger.at/tag/settings/http://bartinger.at/tag/separator/http://bartinger.at/tag/section/http://bartinger.at/tag/score/http://bartinger.at/tag/root/http://bartinger.at/tag/rom/http://bartinger.at/tag/ringermode/http://bartinger.at/tag/rescue/http://bartinger.at/tag/programming-language/http://bartinger.at/tag/playbook/http://bartinger.at/tag/pattern/http://bartinger.at/tag/organisation/http://bartinger.at/tag/optimus/http://bartinger.at/tag/nvflash/http://bartinger.at/tag/modaco/http://bartinger.at/tag/minecraft/http://bartinger.at/tag/market/http://bartinger.at/tag/listview/