如何控制底部工作表的宽度?

9

我需要一个底部弹出框在平板上不占据全部宽度。但是它无视xml中的layout_width属性。我该如何做呢?

我的底部弹出框类:

public class DetailsFragment extends BottomSheetDialogFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //Create fragment root view
        View view = inflater.inflate(R.layout.fragment_details, container, false);
        //Set toolbar
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        Drawable icClose = VectorDrawable.getDrawable(getContext(), R.drawable.ic_close_white_24dp);
        toolbar.setNavigationIcon(icClose);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        toolbar.inflateMenu(R.menu.details);
        RecyclerView rvContent = (RecyclerView) view.findViewById(R.id.rvContent);
        FullExpandedListManager lm = new FullExpandedListManager(getContext());
        rvContent.setLayoutManager(lm);
        rvContent.setHasFixedSize(true);
        rvContent.setAdapter(mAdapter);

        return view;
    }
}
2个回答

6

我不确定这是否是最好的解决方案,但至少对我有效。

public class DetailsFragment extends BottomSheetDialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new BottomSheetDialog(getContext(), getTheme());
    }

    public static class BottomSheetDialog extends android.support.design.widget.BottomSheetDialog {

        public BottomSheetDialog(@NonNull Context context) {
            super(context);
        }

        protected BottomSheetDialog(@NonNull Context context, final boolean cancelable,
                                    OnCancelListener cancelListener) {
            super(context, cancelable, cancelListener);
        }

        public BottomSheetDialog(@NonNull Context context, @StyleRes final int theme) {
            super(context, theme);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            getWindow().setLayout(300 /*our width*/, ViewGroup.LayoutParams.MATCH_PARENT);
        }
    }
}

附注:我尝试在 onStart() 方法中设置对话框宽度,但是它没有生效,我不知道原因。


很棒。像冠军一样工作。 - Jiju Induchoodan
1
只需在 onCreate 中添加以下行:getWindow().setLayout(300 /*我们的宽度*/, ViewGroup.LayoutParams.MATCH_PARENT);,似乎可以为 BottomSheetDialog 解决问题。 - John
更改对话框宽度的完美答案。 - Mostafa Imran
注意:以这种方式进行操作时,我遇到了一些关于底部工作表的奇怪问题。在某些物理设备上(例如 Android 12 上的 Pixel 4a 和 Pixel 6 Pro,但不是 13),它似乎错误地计算了内部宽度,并且一些 UI 元素重叠在屏幕的右侧边缘。这些问题仅出现在物理设备上,而不是虚拟设备上。此外,如果按钮位于 ListView 中,则某些按钮触摸事件将无法注册。撤销此更改后,所有问题都消失了。因此,请自行决定是否使用。 - Adam Burley

2

BottomSheetBehaviour.maxWidth 对我很有帮助。


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