简体   繁体   中英

Listview load on scroll (Android)

I'm developing a chat application and I'm trying to load 10 messages at a time, and when the user scrolls up it loads 10 more. therefore I used stackFromBottom=true to load the messages from the bottom :

<ListView
   android:id="@+id/messagesList"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:transcriptMode="normal"
   android:stackFromBottom="true">

And I have a scroll listener to know when the user reached the top (firstVisibleItem == 0 , ie the first message) so I can load more messages:

messagesList.setOnScrollListener(new AbsListView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {
    }
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        if (firstVisibleItem ==0 && !loading && !startApp) {
            loading = true;
            skip += 10; 
            fetchMessages = new FetchMessages(); //load more items
            fetchMessages.execute(true);
        }
    }
});

The issue is when you scroll up and reach the top, 10 more messages load but the Listview automatically scrolls to the bottom. I want to stay in the exact same position when new items are added to the Listview, just like any regular chat application.

This is the add messages method:

@Override
protected void onPostExecute(String json) {

   if(json!=null){
      ...
      //After Parse JSON ...
      chatMessageAdapter.list.add(0,chatMessage); //add the message to the top of the list
      chatMessageAdapter.notifyDataSetChanged(); //listview scrolls to the bottom afterwards       
   }


   loading = false;
   startApp = false;

}

I tried many of the suggestions in other threads but none of them actually worked. I hope someone could help here.

Many thanks.

what did work for me was that:

// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();

// notify dataset changed or re-assign adapter here

// restore the position of listview
mList.setSelectionFromTop(index, top);

Do note you have to remove android:transcriptMode="normal" from your xml, otherwise it wouldn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM