Center a ListView on its current selection

前端 未结 3 1706
故里飘歌
故里飘歌 2021-02-08 10:16

Does anyone know of a way to center a ListView based on its current selection or selection set with setSelection?

I did see this other StackOverflow question without any

相关标签:
3条回答
  • 2021-02-08 10:25

    You will need to have the scroll view and the view of the item selected. Then you can simply do:

    scrollView.smoothScrollTo(0, selectedView.getTop() - (scrollView.getHeight() / 2) + (selectedView.getHeight() / 2), 0);
    

    This will center the scroll view exactly on selectedView

    0 讨论(0)
  • 2021-02-08 10:33

    I haven't tried any of this but based on the current selection could you use public void smoothScrollByOffset (int offset) to get the view to scroll to where you want so that your selection is in the middle of the view?

    0 讨论(0)
  • 2021-02-08 10:41

    First, get the height of the ListView using getHeight, which returns the height of the ListView in pixels.

    Then, get the height of the row's View using the same method.

    Then, use setSelectionFromTop and pass in half of the ListView's height minus half of the row's height.

    Something like:

    int h1 = mListView.getHeight();
    int h2 = v.getHeight();
    
    mListView.setSelectionFromTop(position, h1/2 - h2/2);
    

    Or, instead of doing the math, you might just pick a constant for the offset from the top, but I would think it might be more fragile on different devices since the second argument for setSelectionFromTop appears to be in pixels rather than device independent pixels.

    I haven't tested this code, but it should work as long as your rows are all roughly the same height.

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