Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android:stackFromBottom="true" does not seem to work perfectly (reverse ListView with Adapter)

Ok let me explain what "does not work perfectly" means.

I have a listview without the android:stackFromBottom="true" parameter. I also have an ArrayAdapter with the regular getItem(position). I call my webserver, get the data on an asc date order.

This way the item in position 0 (top) of the list has the smallest date. And I can scroll top->bottom. Good.

I added android:stackFromBottom and now I see that now you can start scolling from bottom->top but the item in position 0 is still the top item and has the smallest date. So the adapter has not changed its order.

The only way to solve this is to change getItem(getCount()-1-position) inside the adapter. However I add and notify the adapter and the adapter will still add the items to the bottom.

I guess that the structure is ListView -> Adapter -> Row Views so no matter the stackFromBottom value, there is only one child, the adapter. Right?

Anyhow, how can have a ListView with Adapter in reverse order?

like image 963
Diolor Avatar asked Mar 28 '14 16:03

Diolor


2 Answers

A nice elegant way to do this is to override your Adapter.getItem() method to return the items themselves in reverse order.

This is a good pattern for an Adapter as it does not require your data to be sorted differently just for display purposes (there could be overhead in sorting the list, or some other reason why the original order is important in another part of the app).

Instead it is the adapter that displays the change without affecting the underlying data set.

Here is what I used:

@Override
public MyListItemClass getItem(int position)
{
    return super.getItem(getCount() - 1 - position);
}

This is based on @mes's answer to this related question:

  • Display new items at the top of a ListView

Have a look at that thread for some discussion about other possible solutions.

like image 151
Richard Le Mesurier Avatar answered Sep 28 '22 12:09

Richard Le Mesurier


I overestimated android:stackFromBottom power. What it basically does is a similar to "gravity : bottom". It does not add items in reverse order but it just makes the content aligned to the bottom of the listview.

I'm still searching for a reverse adapter solution.

like image 27
Diolor Avatar answered Sep 28 '22 12:09

Diolor