Android ListView y position

后端 未结 3 1561
予麋鹿
予麋鹿 2021-01-07 08:49

It seems like ListView doesn\'t expose its y-position in the same way a ScrollView does. In other words: I need to remember the exact position the ListView was scrolled to

相关标签:
3条回答
  • 2021-01-07 08:50
    Parcelable state = list.onSaveInstanceState();
    
    // do stuff
    
    list.onRestoreInstanceState(state);
    

    Is the only correct way I know of to maintain exact position of a list. The above solution that's marked as correct bumps up/down a few pixels so not really the most professional solution.

    0 讨论(0)
  • 2021-01-07 08:59

    When you are returning from another Activity, the ListView will remain scrolled to its original position that it was at when you left that ListView Activity. If you are updating the contents of the list make sure you just use notifyDataSetChanged() on the adapter, do not re-assign the adapter - this will reset the list to the top.

    Check your onResume method in your ListView Activity, it might be re-assigning a list adapter.

    If you need to remember an arbitrary scroll position that doesn't rely on the Activity stack, I am willing to bet that isn't possible besides just saving the current selected or first visible item. A ListView does not have a defined height. It is relative to both the number of items and content of those items.

    0 讨论(0)
  • 2021-01-07 09:06

    I've used this successfully when saving (in onSaveInstanceState) and restoring (onCreate), when switching orientations:

    Saving:

        int savedPosition = list.getFirstVisiblePosition();
        View firstVisibleView = list.getChildAt(0);
        int savedListTop = (firstVisibleView == null) ? 0 : firstVisibleView.getTop();
    

    Restoring:

       if (savedPosition >= 0) { //initialized to -1
          list.setSelectionFromTop(savedPosition, savedListTop);
        }
    

    This will precisely save the Y position. Well, it misses by a few pixels every once in a while.

    0 讨论(0)
提交回复
热议问题