Я использовал новый BottomSheetDialog, добавленный в Support Library 23.2, но я хочу изменить высоту по умолчанию диалога. Я знаю, что это, вероятно, связано с атрибутом behavior_peekHeight
, который управляет начальной высотой, но как установить его в BottomSheetDialog
, когда у меня нет прямого доступа к BottomSheetBehavior
?
Как изменить высоту по умолчанию BottomSheetDialog?
Ответ 1
Вы можете установить bottomSheetDialogTheme
в своей деятельности, переопределяя атрибут bottomSheetStyle
behavior_peekHeight
:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="bottomSheetDialogTheme">@style/AppBottomSheetDialogTheme</item>
</style>
<style name="AppBottomSheetDialogTheme"
parent="Theme.Design.Light.BottomSheetDialog">
<item name="bottomSheetStyle">@style/AppModalStyle</item>
</style>
<style name="AppModalStyle"
parent="Widget.Design.BottomSheet.Modal">
<item name="behavior_peekHeight">@dimen/custom_peek_height</item>
</style>
Этот же метод можно использовать и для других атрибутов, таких как добавление <item name="behavior_hideable">true</item>
в AppModalStyle
чтобы изменить возможность AppModalStyle
нижнего листа.
Ответ 2
вы можете использовать BottomSheetBehavior
в своем коде
BottomSheetDialog dialog = new BottomSheetDialog(content);
.
.
.
dialog.setContentView(view);
BottomSheetBehavior mBehavior = BottomSheetBehavior.from((View) view.getParent());
mBehavior.setPeekHeight(your dialog height)
dialog.show();
Ответ 3
styles.xml
<style name="BottomSheetDialog" parent="Theme.Design.Light.BottomSheetDialog">
<item name="bottomSheetStyle">@style/bottomSheetStyleWrapper</item>
</style>
<style name="bottomSheetStyleWrapper" parent="Widget.Design.BottomSheet.Modal">
<item name="behavior_peekHeight">500dp</item>
</style>
BottomSheetDialog dialog = new BottomSheetDialog(this, R.style.BottomSheetDialog);
dialog.setContentView(R.layout.layout_bottom_sheet);
dialog.show();
Ответ 4
Другой способ - наследовать BottomSheetDialogFragment
и контролировать, как и когда вы устанавливаете представление содержимого. Подойдя к дереву просмотров, вы можете получить поведение, которое BottomSheetDialog
завершает просмотр содержимого. Это не очень хорошее решение, потому что для этого требуется больше макетов. Важно, что когда состояние нижнего листа STATE_HIDDEN
, мы должны отменить диалог, если мы не будем явно нарушать реализацию, представленную в библиотеке.
После настройки высоты заглядывания, просмотр содержимого должен вызвать requestLayout()
, который действительно является другим макетом.
public class CustomBottomSheetDialogFragment extends BottomSheetDialogFragment {
private BottomSheetBehavior.BottomSheetCallback mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
setStateText(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(getContext(), R.layout.bottom_sheet_dialog_content_view, null);
dialog.setContentView(contentView);
mBottomSheetBehavior = BottomSheetBehavior.from(((View) contentView.getParent()));
if (mBottomSheetBehavior != null) {
mBottomSheetBehavior.setBottomSheetCallback(mBottomSheetBehaviorCallback);
mBottomSheetBehavior.setPeekHeight(peekHeight);
contentView.requestLayout();
}
}
Ответ 5
Объединяя решение Nick и litao, это полная версия того, что мы делаем:
BottomSheetDialog bottomSheet = new BottomSheetDialog(context);
View view = View.inflate(context, R.layout.your_action_sheet, null);
bottomSheet.setContentView(view);
BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(((View) view.getParent()));
bottomSheetBehavior.setPeekHeight(1000);
bottomSheet.show();
Ответ 6
Работа для меня
override fun onStart() {
super.onStart()
dialog?.also {
val bottomSheet = dialog.findViewById<View>(R.id.design_bottom_sheet)
bottomSheet.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT
val behavior = BottomSheetBehavior.from<View>(bottomSheet)
behavior.peekHeight = resources.displayMetrics.heightPixels //replace to whatever you want
view?.requestLayout()
}
}
Ответ 7
Я получил один хак и использовал его.
Если вы хотите сделать программно.
behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View view, int i) {
behavior.setPeekHeight(yourMinHeight);
}
@Override
public void onSlide(@NonNull View view, float v) {
}
});
Спасибо.
Ответ 8
Вот как я решил проблему:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = BottomSheetDialog(context)
val view = View.inflate(context, R.layout.bottom_dialog, null)
val heightInPixels = 500
val params = ViewGroup.LayoutParams(MATCH_PARENT, heightInPixels)
dialog.setContentView(view, params)
return dialog
}
Основной частью является метод setContentView(view, params)
, где вы устанавливаете представление для вашего диалога и параметры макета, в которых вы устанавливаете желаемую высоту.
Ответ 9
Честно говоря, я понятия не имею, почему никто не упомянул эти простые способы:
override fun onResume() {
super.onResume()
dialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED
// or since com.google.android.material:material:1.1.0-beta01
(dialog as? BottomSheetDialog)?.behavior?.state = BottomSheetBehavior.STATE_EXPANDED
}
//or
dialog.behavior.peekheight = YOUR_VALUE
Непосредственно отвечая на вопрос
Q: Как я могу напрямую получить доступ к BottomSheetBehavior?
A:
dialog.behavior.peekheight