0

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 , i.e 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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.