Android ViewPager with RecyclerView works incorrectly inside BottomSheet

后端 未结 7 1021
故里飘歌
故里飘歌 2020-12-13 02:51

When I try to scroll list, sometimes this works incorrect - BottomSheet intercepts the scroll event and hides.

How to reproduce this:

  1. Open Bottom Sheet
7条回答
  •  时光取名叫无心
    2020-12-13 03:36

    There is another approach that does not require modifying BottomSheetBehavior but instead leverages the fact that the BottomSheetBehavior only recognizes the first NestedScrollView with NestedScrollingEnabled it finds. So instead of altering this logic inside BottomSheetBehavior, enable and disable the appropriate scroll views. I discovered this approach here: https://imnotyourson.com/cannot-scroll-scrollable-content-inside-viewpager-as-bottomsheet-of-coordinatorlayout/

    In my case my BottomSheetBehavior was using a TabLayout with a FragmentPagerAdapter so my FragmentPagerAdapter needed the following code:

    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    
            super.setPrimaryItem(container, position, object);
    
            Fragment f = ((Fragment)object);
            String activeFragmentTag = f.getTag();
            View view = f.getView();
    
            if (view != null) {
                View nestedView = view.findViewWithTag("nested");               
                if ( nestedView != null && nestedView instanceof NestedScrollView) {
                    ((NestedScrollView)nestedView).setNestedScrollingEnabled(true);
                }
            }
    
            FragmentManager fm = f.getFragmentManager();
    
            for(Fragment frag : fm.getFragments()) {
    
                if (frag.getTag() != activeFragmentTag) {
                    View v = frag.getView();
                    if (v!= null) {
    
                        View nestedView = v.findViewWithTag("nested");
    
                        if (nestedView!= null && nestedView instanceof NestedScrollView) {
                            ((NestedScrollView)nestedView).setNestedScrollingEnabled(false);
                        }
                    }
                }
            }
    
            container.requestLayout();
        }
    

    Any nested scroll views in your fragments just need to have the "nested" tag.

    Here is a sample Fragment layout file:

    
    
    
        
    
            
    
                
                      
    
              
    
        
    
    
    

提交回复
热议问题