I have a view that contains a ListView which is bound to a cursor adapter. When The cursor content change I want to keep the ListView at the top then in my custom cursor adapter I added :
@Override
protected void onContentChanged() {
// ...
myListView.scrollTo(0, 0);
}
but this doesn't work. Then I read somewhere to queue this action like this :
myListView.post(new Runnable() {
public void run() {
myListView.scrollTo(0, 0);
}
});
but this doesn't work either.
How can I keep the ListView at the top when its content changes?
EDIT:
Just for try, I added a button and called scrollTo() in its onClickListener and it didn't work! What am I missing ?
Instead of scrollTo, try setSelection(0) to get to the top position of list view.
i made functions that could be useful for others for listview scrolling, they work for me in every android version, emulator and device, here itemheight is the fixed height of view in the listview.
int itemheight=60;
public void scrollToY(int position)
{
int item=(int)Math.floor(position/itemheight);
int scroll=(int) ((item*itemheight)-position);
this.setSelectionFromTop(item, scroll);// Important
}
public void scrollByY(int position)
{
position+=getListScrollY();
int item=(int)Math.floor(position/itemheight);
int scroll=(int) ((item*itemheight)-position);
this.setSelectionFromTop(item, scroll);// Important
}
public int getListScrollY()
{
try{
//int tempscroll=this.getFirstVisiblePosition()*itemheight;// Important
View v=this.getChildAt(0);
int tempscroll=(this.getFirstVisiblePosition()*itemheight)-v.getTop();// Important
return tempscroll;
}catch(Exception e){}
return 0;
}
ListView's scrollTo
applies to the ListView
it self as a View
setSelection(0)
does the trick because it applies to the listview's adapter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With