Android

특정 뷰위에 BottomSheet 올리기

그란. 2022. 9. 29. 21:58

 

Bottom Sheet 같은 뷰 만들기

 

개발 과정

  1. PopupWindow 만들기 
  2. BottomSheetBehavior 적용하기

1. PopupWindow 

 

private val popupMenu: PopupWindow by lazy {
    PopupWindow(
        FragmentChatMenuBinding.inflate(layoutInflater).root,
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT,
        true
    )
}

 private fun popupWindow(isShow: Boolean) {
        if (isShow) {
            if (!popupMenu.isShowing) {
                popupMenu.showAtLocation(
                    viewDataBinding.bottom,
                    Gravity.BOTTOM,
                    0,
                    viewDataBinding.bottom.height
                )
            }
        } else {
            if (popupMenu.isShowing) {
                popupMenu.dismiss()
            }
        }
    }

viewDataBidning.bottom => 입력창 ( EditText )

이렇게 입력창 바로 위에 팝업 윈도우를 띄우고 

 

 

2. 끌어 내릴 수 있도록 BottomSheetBehavior 적용

 

FragmentChatMenuBinding xml 파일에 CoordinatorLayout 으로 감싸고 원래 ViewGroup에 아래 behavior 추가 

app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"

 

PopupWindow 수정 

lateinit var bottomSheetBehavior: BottomSheetBehavior<ConstraintLayout>

PopupWindow(
    FragmentChatMenuBinding.inflate(layoutInflater).apply {
        bottomSheetBehavior = from(this.menu)
        bottomSheetBehavior.addBottomSheetCallback(object : BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                if (newState == STATE_HIDDEN) {
                    popupMenu.dismiss()
                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {

            }
        })

        bottomSheetBehavior.isHideable = true
        bottomSheetBehavior.state = STATE_EXPANDED
	... (생략)
)

 

private fun popupWindow(isShow: Boolean) {
    if (isShow) {
        if (!popupMenu.isShowing) {
            bottomSheetBehavior.state = STATE_EXPANDED
        	... (생략)
        }
    } else {
        if (popupMenu.isShowing) {
            popupMenu.dismiss()
        }
    }
}

 

정리하자면

팝업윈도우가 켜졌을때 -> Expand 

끌어서 내리면 ( HIDDEN ) -> 팝업윈도우 : Dismiss