简体   繁体   中英

Close bottom sheet inside fragment from activity

I have a viewpager with 3 fragments inside . And inside fragments I have a recyclerview if I click on recyclerview item it shows bottom sheet with some details of that item. But when I click back button it closes the app. How can I acheive that if I click back button it will close bottom sheet and then app. I can close bottom sheet. But inside fragment there is no onBackPressed method so I can not. Any help is apprecieated.

There is more the one way to achieve this, but I guess it all comes down to this:

Note: Since there is no code I suspect that the bottom sheet is inside of your fragment.

You have to setBottomSheetCallback to the fragment that you have it in:

BottomSheetBehavior.BottomSheetCallback() {
    @Override
    public void onStateChanged(@NonNull View view, int newState) {
        switch (newState) {
            case BottomSheetBehavior.STATE_EXPANDED: {
                // sheet expanded
            }
            break;
            case BottomSheetBehavior.STATE_COLLAPSED: {
                // sheet collapsed
            }
            break;
        }
    }

    @Override
    public void onSlide(@NonNull View view, float v) {

    }
});

Then have a global boolean like isSheetExpanded and set it onStateChanged. (when expanded = true and when collapsed = false)

Your PagerAdapter needs to be aware of this variable something like:

boolean sheetVisible = pagerAdapter.get(fragment).isSheetExpanded;

And finally, onBackPressed() of the Activity that holds the ViewPager you should do something like this:

  @Override
    public void onBackPressed() {
        if (sheetVisible) {
            // collapse bottom sheet
        } else {
            super.onBackPressed();
        }
   }

Without any code, this should be enough to point you in the right direction.

Good luck!

YourFragment :

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    when (bottomSheetBehavior.state) {
                        BottomSheetBehavior.STATE_HALF_EXPANDED -> {
                            closeBottomSheetFragment()
                        }
                        else -> {
                            isEnabled = false
                            requireActivity().onBackPressed()
                        }
                    }
                }
            })
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM