Foggy day

[Android] fragment onbackpressed callback 본문

Android

[Android] fragment onbackpressed callback

jinhan38 2021. 5. 28. 02:09
class FragmentTest : Fragment(){    

    lateinit var onbackPressedCallBack: OnBackPressedCallback
    
    override fun onAttach(context: Context) {
        super.onAttach(context)
        onbackPressedCallBack = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                ToastUtil.showMessage("백 버튼 클릭")
                if (bottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED) {
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN
                }
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(this, onbackPressedCallBack)
    }
    
    override fun onDetach() {
        super.onDetach()
        onbackPressedCallBack.remove()
    }
}