Maintain scroll position when adding to ListView with reverse endless-scrolling

雨燕双飞 提交于 2019-12-03 01:48:52

I have figured this out. Wherever it is that you are getting new data I call the following before changing data in the adapter:

int firstVisibleItem = list.getFirstVisiblePosition();
int oldCount = adapter.getCount();
View view = list.getChildAt(0);
int pos = (view == null ? 0 :  view.getBottom());

Then I call:

adapter.setData(data);

list.setSelectionFromTop(firstVisibleItem + adapter.getCount() - oldCount + 1, pos);
Atul O Holic

First get the firstVisiblePosition (or the Last one since its upside down. Yo got to try and check it yourself) and then get the top of the View which is added to the List and then using setSe;ectionFromTop() method, you can scroll to the desired location.

Code:

int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0); //or upside down (list.size - 1)
int top = (v == null) ? 0 : v.getTop(); //returns the top of the view its Y co-ordinates. [Doc][1]
mList.setSelectionFromTop(index, top);

Source.

Edit to account for additional information:

I think I've found your issue. I replicated your described use cases by using a standalone list as the only view in XML:

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</ListView>

I fixed the problem to follow your desired use cases by nesting the layout in a parent layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</FrameLayout>

after you insert the record in your adapter you can try to use

   yourListView.setSelection(yourAdapter.getCount() - 1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!