One of the UI patterns that improve lists usability is dividing items into sections. The section might be the first letter of the main text on the list item, date formatted and rounded in a specific way or whatever makes sense for your data.
From the technical point of view you can either add the header view to every list item and show and hide them as needed or create the separate view for header and regular list item and register multiple view types in your Adapter. Both options were described in details by +Cyril Mottier in excellent ListView Tips & Tricks #2: Sectioning Your ListView blog post.
If you choose the second approach, you’ll have to decide what to return from your Adapter
’s getItem
and getItemId
methods for items representing sections. If your sections are not supposed to be clickable, you might implement your Adapter
like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
And your onListItemClickListener
like this:
1 2 3 4 5 6 7 |
|
If you do so, the Android has a nasty surprise for you:
1 2 3 4 5 6 7 8 9 |
|
The only way this can happen is getting null
from Adapter.getItem()
, but this method will be called only for disabled items, right?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Wrong:
1 2 3 4 5 6 7 8 9 10 |
|
It’s very difficult to reproduce this error manually, especially if tapping the list item does something more than writing to logcat, but I investigated this issue, because the stack traces above appeared in crash reports on Google Analytics, so several people managed to click exactly wrong area at the wrong time.
I didn’t investigate the issue thoroughly, but it seems there must be some disparity between checking the isEnabled
method and getting the item. If I ever dive into ListView
code, I’ll definitely write about it. If you want to reproduce or investigate the issue yourself, compile this project and run the monkey:
1
|
|
So what can we do? First option is checking the Adapter.isEnabled()
in your onListItemClick
listener, which is yet another kind of boilerplate you have to add to your Android code, but it’s super easy to add. The other option is going with the first sectioning approach, i.e. putting section as a part of the clickable list item, but it might not work for your use case (for example adapter with multiple item types).