Android底部sheet设计

Android bottom sheet design

有什么方法可以设计底部 sheet 片段如下:

我需要将底部 sheet 的宽度设置为屏幕的 1/4。可以实现吗?

感谢您的帮助。

像往常一样为你的底部创建一个布局文件sheet,并将宽度设置为你需要的:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/sheet_background"
    android:layout_width="100dp"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="100dp"
        android:layout_height="match_parent"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
        app:behavior_peekHeight="150dp"
        android:id="@+id/drag_up_from_here">

        <!-- Bottom sheet contents here -->

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

然后要使其固定在右侧,您可以通过编程将底部 sheet 附加到您的布局。这就是我添加底部 sheets:

的方式
    val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater
    val bottomSheet = inflater.inflate(R.layout.bottomsheet_layout, null)
    val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet.findViewById<View>(R.id.drag_up_from_here)

    // Allow user to drag part of bottom sheet
    bottomSheet.findViewById<LinearLayout>(R.id.drag_up_from_here).setOnClickListener {
        if (bottomSheetBehavior.getState() != BottomSheetBehavior.STATE_EXPANDED) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED)
        } else {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED)
        }
    }

    // Create popup window
    val bottomSheetPopup = PopupWindow(popupViewLower,
                                    LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.MATCH_PARENT,
                                    false)

    // Get the view you want the bottom sheet added to
    val currentView = findViewById<ConstraintLayout>(R.id.main_view)

    // Display the popup window
    bottomSheetPopup.showAtLocation(currentView, Gravity.BOTTOM, currentView.measuredWidth, 0)

在屏幕右侧获取的关键是这部分:

bottomSheetPopup.showAtLocation(currentView, Gravity.BOTTOM, currentView.measuredWidth, 0)

其中 currentView.measueredWidth 作为 x 值传递,将底部 sheet 一直向右移动。

编辑:我意识到您还要求宽度正好是屏幕宽度的 1/4。为此,以编程方式将底部 sheet 布局的宽度设置为 currentView.measuredWidth / 4。这个 post 很好地解释了这一点:Android view layout_width - how to change programmatically?

您可以使用 this library. Or just make the same CornerSheetBehavior 获得相同的结果。如您所见,它只是一个 BottomSheetBehavior,管理 translationX 视图