Сделать нижний лист диалога полноэкранным над строкой состояния

Недавно я использовал android.support.design.widget.BottomSheetDialogFragment. Я хотел сделать что-то похожее на приложение контактов Google, его BottomSheet может накладываться на панель инструментов и строку состояния. Однако, когда я использую BottomSheetDialogFragment для реализации этого, получается следующее: Моя реализация

Как видите, панель инструментов активности все еще видна. Вот мой код BottomSheetDialogFragment:

public class KeyDetailFragment extends BottomSheetDialogFragment {
    private BottomSheetBehavior.BottomSheetCallback mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() {
        @Override
        public void onStateChanged(@NonNull View bottomSheet, int newState) {
            if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                dismiss();
            }
        }

        @Override
        public void onSlide(@NonNull View bottomSheet, float slideOffset) {

        }
    };

    @Override
    public void setupDialog(Dialog dialog, int style) {
        super.setupDialog(dialog, style);
        View contentView = View.inflate(getActivity(), R.layout.sheet_key, null);
        dialog.setContentView(contentView);
        View parent = (View) contentView.getParent();
        parent.setFitsSystemWindows(true);
        BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(parent);
        contentView.measure(0, 0);
bottomSheetBehavior.setPeekHeight(contentView.getMeasuredHeight());

        CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) parent.getLayoutParams();
        if (params.getBehavior() instanceof BottomSheetBehavior) {
                 ((BottomSheetBehavior)params.getBehavior()).setBottomSheetCallback(mBottomSheetBehaviorCallback);
        }
        params.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
        parent.setLayoutParams(params);
    }
}

Я сослался на источник и нашел интересующий меня атрибут:

private static int getThemeResId(Context context, int themeId) {
    if (themeId == 0) {
        // If the provided theme is 0, then retrieve the dialogTheme from our theme
        TypedValue outValue = new TypedValue();
        if (context.getTheme().resolveAttribute(
                R.attr.bottomSheetDialogTheme, outValue, true)) {
            themeId = outValue.resourceId;
        } else {
            // bottomSheetDialogTheme is not provided; we default to our light theme
            themeId = R.style.Theme_Design_Light_BottomSheetDialog;
        }
    }
    return themeId;
}

атрибут bottomSheetDialogTheme здесь может изменить стиль нижнего листа, но я не знаю, как это изменить, и я сомневаюсь, что это сработает. Может ли кто-нибудь дать мне решение о том, как добиться того, чтобы он мог накладываться на панель инструментов и строку состояния?


person Jian Guo    schedule 05.04.2016    source источник
comment
Такая же проблема, вы нашли какое-то решение этой проблемы?   -  person nipun.birla    schedule 19.07.2016
comment
@nipun.birla Нет, я еще не нашел, хотя прошло около 3 месяцев   -  person Jian Guo    schedule 20.07.2016
comment
Думаю причина в высоте. Проверьте это: stackoverflow.com/ вопросы/35711808/.   -  person Alexander Skvortsov    schedule 22.11.2016
comment
У меня такая же проблема. но не в состоянии найти хорошее решение.   -  person Sree...    schedule 24.07.2018


Ответы (3)


Попробуй это. Меня устраивает.

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


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

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

    View parent = (View) inflatedView.getParent();
    parent.setFitsSystemWindows(true);
    BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(parent);
    inflatedView.measure(0, 0);
    DisplayMetrics displaymetrics = new DisplayMetrics();        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int screenHeight = displaymetrics.heightPixels;
    bottomSheetBehavior.setPeekHeight(screenHeight);

    if (params.getBehavior() instanceof BottomSheetBehavior) {
        ((BottomSheetBehavior)params.getBehavior()).setBottomSheetCallback(mBottomSheetBehaviorCallback);
    }

    params.height = screenHeight;
    parent.setLayoutParams(params);
}
person Vaigunth    schedule 14.10.2016
comment
В этом решении следует отметить одну вещь: displayMetrics.heightPixels будет включать высоту панели уведомлений, поэтому это немного обрежет нижнюю часть. Я использовал это, чтобы рассчитать высоту панели уведомлений. private int getStatusBarHeight() { Rect rectangle = new Rect(); Window window = getActivity().getWindow(); window.getDecorView().getWindowVisibleDisplayFrame(rectangle); return rectangle.top; } - person C Nick; 13.04.2017
comment
Редактировать: DisplayMetrics displaymetrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); Кому: DisplayMetrics displaymetrics = getActivity().getResources().getDisplayMetrics() - person roghayeh hosseini; 15.08.2018
comment
Можно ли обрабатывать макет координатора и панель приложений в xml? - person Mahdi; 10.12.2019

Не смог найти решение этой проблемы, но могу предложить альтернативу, которая помогла мне достичь той же цели. Вот ссылка: http://www.hidroh.com/2016/06/17/bottom-sheet-everything/

В статье объясняется создание активности нижнего листа и добавление к ней фоновой тени.

person nipun.birla    schedule 20.07.2016
comment
Данная ссылка, безусловно, является альтернативой моей цели, добавление тени на фоне действительно сложно. - person Jian Guo; 20.07.2016

Это было проще всего и сработало для меня, просто расширьте BottomSheetDialog и установите для BottomSheetBehavior значение BottomSheetBehavior.STATE_EXPANDED.

Маленький хак — название макета android.support.design.R.id.design_bottom_sheet взято из библиотеки дизайна поддержки Android.

class BottomSheetDialogExpanded(context: Context) : BottomSheetDialog(context) {

    private lateinit var mBehavior: BottomSheetBehavior<FrameLayout>

    override fun setContentView(view: View) {
        super.setContentView(view)
        val bottomSheet = window.decorView.findViewById<View>(android.support.design.R.id.design_bottom_sheet) as FrameLayout
        mBehavior = BottomSheetBehavior.from(bottomSheet)
        mBehavior.state = BottomSheetBehavior.STATE_EXPANDED
    }

    override fun onStart() {
        super.onStart()
        mBehavior.state = BottomSheetBehavior.STATE_EXPANDED
    }
}
person Akhil    schedule 04.01.2018