Scroll a ListView by pixels in Android

后端 未结 5 1424
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 08:50

I want to scroll the a ListView in Android by number of pixels. For example I want to scroll the list 10 pixels down (so that the first item on the list has its top

5条回答
  •  无人共我
    2021-02-06 09:46

    Here is some code from my ListView subclass. It can easily be adapted so it can be used in Activity code.

    getListItemsHeight() returns the total pixel height of the list, and fills an array with vertical pixel offsets of each item. While this information is valid, getListScrollY() returns the current vertical pixel scroll position, and scrollListToY() scrolls the list to pixel position. If the size or the content of the list changes, getListItemsHeight() has to be called again.

    private int m_nItemCount;
    private int[] m_nItemOffY;
    
    private int getListItemsHeight() 
    {  
        ListAdapter adapter = getAdapter();  
        m_nItemCount = adapter.getCount();
        int height = 0;
        int i;
    
        m_nItemOffY = new int[m_nItemCount];
    
        for(i = 0; i< m_nItemCount; ++i){ 
            View view  = adapter.getView(i, null, this);  
    
            view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));  
    
            m_nItemOffY[i] = height;
            height += view.getMeasuredHeight();
        }  
    
        return height;  
    }  
    
    private int getListScrollY()
    {
        int pos, nScrollY, nItemY;
        View view;
    
        pos = getFirstVisiblePosition();
        view = getChildAt(0);
        nItemY = view.getTop();
        nScrollY = m_nItemOffY[pos] - nItemY;
    
        return nScrollY;
    }
    
    private void scrollListToY(int nScrollY)
    {
        int i, off;
    
        for(i = 0; i < m_nItemCount; ++i){
            off = m_nItemOffY[i] - nScrollY;
            if(off >= 0){
                setSelectionFromTop(i, off);
                break;
            }
        }
    }
    

提交回复
热议问题