列表视图加载滚动(Android)

时间:2016-12-23 21:41:14

标签: android listview load

我正在开发一个聊天应用程序,我正在尝试一次加载10条消息,当用户向上滚动时,它会再加载10条消息。因此我使用stackFromBottom = true从底部加载消息:

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

我有一个滚动监听器,知道用户何时到达顶部(firstVisibleItem == 0,即第一条消息),以便我可以加载更多消息:

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);
        }
    }
});

问题是,当您向上滚动并到达顶部时,会再加载10条消息,但Listview会自动滚动到底部。当新项目添加到Listview时,我希望保持完全相同的位置,就像任何常规聊天应用程序一样。

这是添加消息方法:

@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;

}

我尝试了其他线程中的许多建议,但其中没有一个真正起作用。我希望有人能在这里提供帮助。

非常感谢。

1 个答案:

答案 0 :(得分:0)

对我有用的是:

// 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);

请注意你必须从你的xml中删除android:transcriptMode =“normal”,否则它将无效。

相关问题