How can I put a ListView into a ScrollView without it collapsing?

后端 未结 27 3257
轮回少年
轮回少年 2020-11-21 05:24

I\'ve searched around for solutions to this problem, and the only answer I can find seems to be \"don\'t put a ListView into a ScrollView\". I have yet to see any real expl

27条回答
  •  情书的邮戳
    2020-11-21 05:46

    There are two issue when using a ListView inside a ScrollView.

    1- ListView must fully expand to its children height. this ListView resolve this:

    public class ListViewExpanded extends ListView
    {
        public ListViewExpanded(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            setDividerHeight(0);
        }
    
        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST));
        }
    }
    

    Divider height must be 0, use padding in rows instead.

    2- The ListView consumes touch events so ScrollView can't be scrolled as usual. This ScrollView resolve this issue:

    public class ScrollViewInterceptor extends ScrollView
    {
        float startY;
    
        public ScrollViewInterceptor(Context context, AttributeSet attrs)
        {
            super(context, attrs);
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent e)
        {
            onTouchEvent(e);
            if (e.getAction() == MotionEvent.ACTION_DOWN) startY = e.getY();
            return (e.getAction() == MotionEvent.ACTION_MOVE) && (Math.abs(startY - e.getY()) > 50);
        }
    }
    

    This is the best way I found to do the trick!

提交回复
热议问题