Center a ListView on its current selection

前端 未结 3 1705
故里飘歌
故里飘歌 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: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.

提交回复
热议问题