ListView in BottomSheet

前端 未结 8 2357
梦毁少年i
梦毁少年i 2020-12-13 07:39

I ran into a problem where I had a simple ListView in a BottomSheet and ListView had enough items to fill the screen and scroll even m

8条回答
  •  情话喂你
    2020-12-13 07:44

    The solution is to extend the ListView like this:

    public class BottomSheetListView extends ListView {
        public BottomSheetListView (Context context, AttributeSet p_attrs) {
            super (context, p_attrs);
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            return true;
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent ev) {
            if (canScrollVertically(this)) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onTouchEvent(ev);
        }
    
        public boolean canScrollVertically (AbsListView view) {
            boolean canScroll = false;
    
            if (view !=null && view.getChildCount ()> 0) {
                boolean isOnTop = view.getFirstVisiblePosition() != 0 || view.getChildAt(0).getTop() != 0;
                boolean isAllItemsVisible = isOnTop && view.getLastVisiblePosition() == view.getChildCount();
    
                if (isOnTop || isAllItemsVisible) {
                    canScroll = true;
                }
            }
    
            return  canScroll;
        }
    }
    

    Then in your layout file bottom_sheet_view.xml:

    
    
    
        
    
    
    

    Then finally, in your Activity/Fragment:

    BottomSheetDialog dialog = new BottomSheetDialog(context);
    dialog.setContentView(R.layout.bottom_sheet_view);
    
    BottomSheetListView listView = (BottomSheetListView) dialog.findViewById(R.id.listViewBtmSheet);
    // apply some adapter - add some data to listview
    
    dialog.show();
    

    This will provide a BottomSheet that is fully working with ListView scroll.

提交回复
热议问题