Add new items to top of list view on Android?
Android has the transcript mode to allow to automatically scroll a list view to the bottom when new data is added to the adapter.
Can this be somehow reversed so that new items are automatically added at the top of the list ("inverse transcript mode")
Method stackFromBottom seems about right, but does not do the auto-scrolling on input change.
Does anyone have some example code where a list is constantly adding stuff that gets always inserted at the top? Am I on the right track here?
Update
Thanks for the answers, that made me think more. Actually. I want to have new entries to appear at the top, but the screen still show the item the user is looking at. The user should actively scroll to the top to view the new items. So I guess that transcript mode is not what I want.
Solution 1:
Hmm, well, if I was going to try this, I'd do something like the following:
List items = new ArrayList();
//some fictitious objectList where we're populating data
for(Object obj : objectList) {
items.add(0, obj);
listAdapter.notifyDataSetChanged();
}
listView.post(new Runnable() {
@Override
public void run() {
listView.smoothScrollToPosition(0);
}
}
I don't know for certain that this will work, but it seems logical. Basically, just make sure to add the item at the beginning of the list (position 0), refresh the list adapter, and scroll to position (0, 0).
Solution 2:
instead of this:
items.add(edittext.getText().toString());
adapter.notifyDataSetChanged();
you should try that (works for me):
listview.post(new Runnable() {
@Override
public void run() {
items.add(0, edittext.getText().toString());
adapter.notifyDataSetChanged();
listview.smoothScrollToPosition(0);
}
});
Solution 3:
Shouldn't it be enough to just add a smoothScrollToPosition(0)
whenever stuff gets added to the ListView? Don't think there's an automatic scroll option.
Solution 4:
I spent several hours attempting to accomplish the same thing. Essentially, this acts like a chat app where the user scrolls up to view older messages at the top of the list.
The problem is that, you want to dynamically add another 50 or 100 records to the top but the scrolling should be continuous from where the prepended items were added.
The moment you do a notifyDataSetChanged
, the ListView will automatically position itself at the first item in your data set and NOT at the position that preceded the position where the new items got inserted.
This makes it look like your list just jumped 50 or 100 records. I believe TranscriptMode set to normal is not the solution. The listview needs to function as a normal listview and you need to programmatically scroll to the bottom of the list to simulate the TranscriptMode as it functions under "normal".
Solution 5:
Try to use
LinkedList items = new LinkedList<Object>();
//some fictitious objectList where we're populating data
for(Object obj : objectList) {
items.addFirst(obj);
}
listAdapter.notifyDataSetChanged();