0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Android] BottomSheetDialog の高さを設定する

Last updated at Posted at 2023-10-15

BottomSheetDialogとは

下から出てくるモーダルのようなDialogです。

base_dialog

ソースコード
https://github.com/nishimy432/BottomSheetDialogSample/blob/main/app/src/main/java/com/example/bottomsheetdialogsample/FirstBottomSheetDialogFragment.kt

初期値の高さを調整する

peekHeightに初期値にしたい高さを設定して、stateBottomSheetBehavior.STATE_COLLAPSEDにします。

FirstBottomSheetDialogFragment.kt
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    val bottomSheetDialog = BottomSheetDialog(requireContext())

    bottomSheetDialog.setOnShowListener { dialog ->
        (dialog as? BottomSheetDialog)?.findViewById<FrameLayout>(R.id.design_bottom_sheet)
            ?.let {
                BottomSheetBehavior.from(it).apply {
                    val displayHeight = getFullScreenHeight() - getStatusBarHeight()
                    peekHeight = (displayHeight * 0.5).toInt()
                    state = BottomSheetBehavior.STATE_COLLAPSED
                }
            }
    }
}

private fun getFullScreenHeight(): Int {
    // ・・・
}

private fun getStatusBarHeight(): Int {
    // ・・・
}

BottomSheetBehavior.STATE_COLLAPSEDは折りたたまれている状態、つまりpeekHeightの高さの時の状態です。
peekHeightは普通に数値で指定することができますが、今回は画面サイズの50%という指定をしています。

画面の高さを取得するコード
    private fun getFullScreenHeight(): Int {
        val manager = requireContext().getSystemService(Context.WINDOW_SERVICE) as WindowManager

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val metrics = manager.currentWindowMetrics
            metrics.bounds.height()
        } else {
            val metrics = DisplayMetrics()
            manager.defaultDisplay.getRealMetrics(metrics)
            metrics.heightPixels
        }
    }

    private fun getStatusBarHeight(): Int {
        val outRect = Rect()
        requireActivity().window.decorView.getWindowVisibleDisplayFrame(outRect)
        return outRect.top
    }

結果

初期値を設定した時のgif

参考

BottomSheetDialog - Android Developers
【Kotlin】BottomSheetDialogを触ってみた
【Kotlin/Android Studio】画面(スクリーン)の横幅を取得する方法!デバイスサイズ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?