Android BottomSheetDialogFragment无法完全展开

35
我有以下测试底部表单实现。当我将peekHeight设置为小于500的值时,它可以工作。但是在某个值之后,无论增加多少peek高度都不会改变底部表单的扩展方式,只能手动拖动。如何以编程方式设置peekHeight,以确保底部表单自动扩展到peek高度。 enter image description here bottom_sheet_dialog_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/locUXCoordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/locUXView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:orientation="vertical"
        app:behavior_hideable="false"
        app:behavior_peekHeight="0dp"
        app:layout_behavior="@string/bottom_sheet_behavior">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="1 Value" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="2 Value" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="3 Value" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="4 Value" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="5 Value" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="6 Value" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="7 Value" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="8 Value" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="9 Value" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="First Value" />
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

Java代码

public class MyBottomSheetDialogFragment extends BottomSheetDialogFragment {

    private static BottomSheetBehavior bottomSheetBehavior;
    private static View bottomSheetInternal;
    private static MyBottomSheetDialogFragment INSTANCE;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                BottomSheetDialog d = (BottomSheetDialog) dialog;
                CoordinatorLayout coordinatorLayout = (CoordinatorLayout)d.findViewById(R.id.locUXCoordinatorLayout);
                bottomSheetInternal = d.findViewById(R.id.locUXView);
                bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetInternal);
                bottomSheetBehavior.setPeekHeight(bottomSheetInternal.getHeight());
                bottomSheetInternal.requestLayout();
                coordinatorLayout.getLayoutParams().height = bottomSheetInternal.getHeight();
                Toast.makeText(getActivity(), "Height is" + bottomSheetInternal.getHeight() + "  " + coordinatorLayout.getLayoutParams().height, Toast.LENGTH_LONG).show();

            }
        });
        INSTANCE = this;
        return inflater.inflate(R.layout.bottom_sheet_dialog_main, container, false);
    }
}

1
你应该意识到,"窥视高度"是指被"折叠"的表格的高度,只显示其中一部分。如果将"窥视高度"设置为表格本身的高度(或更高)...那么整个"窥视"就没有意义了。你能否解释一下你想要做什么? - David Medenjak
谢谢。是的,我意识到 peekHeight 是为折叠视图设置的。无论如何,我已经成功纠正了这个问题。 - Nandish A
这一行代码对我很有帮助: coordinatorLayout.getLayoutParams().height = bottomSheetInternal.getHeight(); - Andrii Kovalchuk
11个回答

44

在onCreateView中使用此代码。

getDialog().setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            BottomSheetDialog d = (BottomSheetDialog) dialog;
            FrameLayout bottomSheet = (FrameLayout) d.findViewById(R.id.design_bottom_sheet);
            CoordinatorLayout coordinatorLayout = (CoordinatorLayout) bottomSheet.getParent();
            BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
            bottomSheetBehavior.setPeekHeight(bottomSheet.getHeight());
            coordinatorLayout.getParent().requestLayout();
        }
    });

1
在我的情况下,这些代码应该在 onActivityCreated 中被调用,然后才能正常工作。 - Kevin
3
好的,我会尽力进行翻译。根据您的要求,以下是需要翻译的内容:Nice solution worked with me, I put the code in onViewCreated() - Mohamed ElSawaf

21

我找到了另一个解决方案。也许对于未来的读者来说,这可能很有用。

@Override
public void setupDialog(Dialog dialog, int style) {
    super.setupDialog(dialog, style);
    final View root = View.inflate(getContext(), R.layout.fragment_bottom_sheet_choose_time, null);
    dialog.setContentView(root);
    initView(root);

    CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) ((View) root.getParent()).getLayoutParams();
    CoordinatorLayout.Behavior behavior = params.getBehavior();

    if (behavior != null && behavior instanceof BottomSheetBehavior) {
        mBottomSheetBehavior = (BottomSheetBehavior) behavior;
        mBottomSheetBehavior.setBottomSheetCallback(mBottomSheetBehaviorCallback);

        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                root.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                int height = root.getMeasuredHeight();
                mBottomSheetBehavior.setPeekHeight(height);
            }
        });
    }
}

正如@Anthonyeef所提到的,这里的ViewTreeObserver旨在在视图实际测量后获取准确的高度,并且为了提高性能而移除了GlobalOnLayoutListener

但是,请在生产环境之前在不同的设备和屏幕上测试此解决方案,因为如果您底部表单中的内容高于屏幕,则可能会产生一些奇怪的滑动行为。


1
这个答案真的解决了我的问题。如果能再多解释一些就更好了。例如,我搜索并自己测试后,最终发现ViewTreeObserver旨在在视图实际测量后获取精确的测量高度,并且GlobalOnLayoutListener已被删除以提高性能。 - Anthonyeef
我收到了一些崩溃报告,其中转换为CoordinatorLayout.LayoutParams失败。似乎在某些设备的某些情况下,view.getParent()返回LinearLayout而不是CoordinatorLayout。目前,崩溃报告仅适用于某些Android 8.0设备。 - Catalin Morosan
setupDialogonCreateDialog之间有什么区别? - ysfcyln

17

Kotlin安全实现的方式是:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    dialog.setOnShowListener {
        val dialog = it as BottomSheetDialog
        val bottomSheet = dialog.findViewById<View>(R.id.design_bottom_sheet)
        bottomSheet?.let { sheet ->
            dialog.behavior.peekHeight = sheet.height
            sheet.parent.parent.requestLayout()
        }
    }
}

注意: 不需要将您的布局包装在协调布局中。

非常好用。


12

通过更深入的UI检查,我们发现还有一个CoordinatorLayout包装了我们的协调布局。父CoordinatorLayout具有一个带有ID design_bottom_sheetFrameLayout和一个BottomSheetBehavior。由于design_bottom_sheet ID下的FrameLayout具有match_parent高度,我们上面的代码设置的Peek Height受到了限制。

通过设置ID为design_bottom_sheetFrameLayout的Peek Height,解决了此问题。

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    getDialog().setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            BottomSheetDialog d = (BottomSheetDialog) dialog;
            coordinatorLayout = (CoordinatorLayout) d.findViewById(R.id.locUXCoordinatorLayout);
            bottomSheetInternal = d.findViewById(R.id.locUXView);
            bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetInternal);
            bottomSheetBehavior.setHidable(false);
            BottomSheetBehavior.from((View)coordinatorLayout.getParent()).setPeekHeight(bottomSheetInternal.getHeight());
            bottomSheetBehavior.setPeekHeight(bottomSheetInternal.getHeight());
            coordinatorLayout.getParent().requestLayout();

        }
    });

这个解决方案在 R.id.locUXCoordinatorLayout 中出现错误,无法解析符号。我们应该在这里使用哪个 R..? - Amritpal Singh
locUXCoordinatorLayout,这是我视图中的ID。您的视图可能没有它。请查看我在问题中附加的代码。如果解决了您的问题,请赞同我的答案。 - Nandish A

6

感谢 @athysirus 提供的简洁方法。以下是我最终得出的 Kotlin 示例,如果有人想要参考。

需要注意的是,在完成后还应删除全局布局侦听器。

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    view.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            val bottomSheet = (dialog as BottomSheetDialog).findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
            BottomSheetBehavior.from<View>(bottomSheet).apply {
                state = BottomSheetBehavior.STATE_EXPANDED
                peekHeight = 0
            }
            view.viewTreeObserver.removeOnGlobalLayoutListener(this)
        }
    })

但是这个解决方案会带来另一个问题——在交互式地将BottomSheetDialog向下移动后,背景窗口仍然变暗。 - Gregory
是的,它仍然变暗了。 - Happy Singh

1

这是我在 BottomSheetDialogFragment 中设置底部视图的 peek_heightlayout_height 的方法。

dialog?.setOnShowListener {
                val dialog = dialog as BottomSheetDialog
                val bottomSheet = dialog.findViewById<FrameLayout>(R.id.design_bottom_sheet)
                val coordinatorLayout = bottomSheet?.parent as? CoordinatorLayout
                val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet)
                bottomSheet?.viewTreeObserver?.addOnGlobalLayoutListener {
                    bottomSheet.viewTreeObserver.removeOnGlobalLayoutListener {}
                    bottomSheetBehavior.peekHeight = getPopupHeight(.5f)
                    val params = bottomSheet.layoutParams
                    params.height = getPopupHeight(1f)
                    bottomSheet.layoutParams = params
                    coordinatorLayout?.parent?.requestLayout()
                }
            }

这个方法用于获取屏幕高度的百分比。
 private fun getPopupHeight(percent: Float): Int {
        val displayMetrics = DisplayMetrics()
        activity?.windowManager?.defaultDisplay?.getMetrics(displayMetrics)
        return (displayMetrics.heightPixels * percent).toInt()
    }

1

这是一篇 Kotlin 相关的解决方案,灵感来自于Nandish A在其文章中的详细阐述。首先,看一下布局:

<androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/container_root"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/bottom_sheet"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:behavior_hideable="false"
            app:behavior_peekHeight="0dp"
            app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

                  <!-- content of the bottom sheet -->

        </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

然后将此放入您的BottomSheetDialogFragment中:

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        // ...        

        dialog.setOnShowListener {

            val root = dialog.find<CoordinatorLayout>(R.id.container_root)
            val bottomSheetInternal = root.find<ConstraintLayout>(R.id.bottom_sheet)

            val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetInternal)
            bottomSheetBehavior.isHideable = false
            BottomSheetBehavior.from(root.parent as View).peekHeight = root.height
            bottomSheetBehavior.peekHeight = root.height
            root.parent.requestLayout()
        }

        // ...
    }

0
你可以在编程中调用BottomSheetBehaviorsetFitToContents(true)方法,使其不会完全展开,高度将等于底部表格布局的高度。请确保您的布局高度设置为wrap_content

0

这段代码是答案的组合。因为有些答案对我来说不起作用。

在XML文件ids.xml中:

<item name="sheet_parent_container" type="id" />

在 XML 布局中:

<?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"
    android:id="@id/sheet_parent_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom">

    **Dialog content here!**

</androidx.coordinatorlayout.widget.CoordinatorLayout>

在 BottomSheetDialogFragment.kt 文件中:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    ...

    setPeekHeight(view)
}

/**
 * Function for disable half height display after screen rotation.
 */
private fun setPeekHeight(view: View) {
    val parentContainer = view.findViewById<CoordinatorLayout>(R.id.sheet_parent_container)

    dialog?.setOnShowListener {
        val dialogParent = parentContainer.parent as View
        BottomSheetBehavior.from(dialogParent).peekHeight = parentContainer.height
        dialogParent.requestLayout()
    }
}

0

这对我很有帮助!我的类继承了BottomSheetDialogFragment

@Override
public void onStart()
{
    super.onStart();
    Dialog dialog = getDialog();

    if (dialog != null)
    {
        View bottomSheet = dialog.findViewById(R.id.bottom_sheet);
        bottomSheet.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
    }
    View view = getView();
    view.post(() -> {
        View bottomSheet = dialog.findViewById(R.id.bottom_sheet);
        View parent = (View) view.getParent();
        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) (parent).getLayoutParams();
        CoordinatorLayout.Behavior behavior = params.getBehavior();
        BottomSheetBehavior bottomSheetBehavior = (BottomSheetBehavior) behavior;
        bottomSheetBehavior.setPeekHeight(view.getMeasuredHeight());
        ((View) bottomSheet.getParent()).setBackgroundColor(Color.TRANSPARENT);
    });
}

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View view = inflater.inflate(R.layout.screen_delivery_type, container, false);

    getDialog().setOnShowListener(new DialogInterface.OnShowListener()
    {
        @Override
        public void onShow(DialogInterface dialog)
        {
            BottomSheetDialog d = (BottomSheetDialog) dialog;
            FrameLayout bottomSheet = (FrameLayout) d.findViewById(R.id.bottom_sheet);
            CoordinatorLayout coordinatorLayout = (CoordinatorLayout) bottomSheet.getParent();
            BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
            bottomSheetBehavior.setPeekHeight(bottomSheet.getHeight());
            bottomSheetBehavior.setFitToContents(true);
            bottomSheetBehavior.setExpandedOffset(0);
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            coordinatorLayout.getParent().requestLayout();
        }
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接