- Как я могу установить половину расширенного состояния для моего BottomSheet
- 4 ответа
- Hands-on with Material Components for Android: Bottom Sheets
- Part 3 of a series covering practical usage of Material Components for Android
- Setting up a Material Components theme for Android
- Attribute by attribute
- Basic usage 🏁
- Standard Bottom Sheet
- Modal Bottom Sheet
- Adjusting behavior ⚙️
- Applying attributes
- The attributes
- A word on modal dismiss animations
- Setting (and saving) state 💾
- Setting state
- Retaining attribute state on configuration change
- Listening for state change and slide callbacks 👂
- Theming 🎨
- Color
- Typography
- Shape
- More resources 📚
- Android bottom sheet half expanded
Как я могу установить половину расширенного состояния для моего BottomSheet
У меня есть макет с нижним листом.
Макет нижнего листа
Мне необходимо, чтобы мой нижний лист открывал первую половину, а после перетаскивания он открывается на весь экран. Как это делается в приложении Google Maps. Но я понятия не имею, как это сделать.
4 ответа
Лучше использовать каркас с его полным потенциалом. В официальной документации говорится о методе setFitToContents:
Устанавливает, определяется ли высота раскрываемого листа высотой его содержимого или расширяется в два этапа (половина высоты родительского контейнера, полная высота родительского контейнера). По умолчанию установлено значение true.
Поэтому все, что вам нужно, это установить setFitToContent в false с помощью:
С этим трехстрочным кодом нижний лист сначала расширяется до 60% экрана, а затем полностью расширяется до 100%.
Надеюсь, это поможет!
Просто установите для состояния BottomSheetBehaivor значение BottomSheetBehavior.STATE_HALF_EXPANDED . Также, если вам нужно после полного раскрытия позволить пользователю снова вернуться в полуразвернутый режим, вам нужно установить высоту просмотра равной половине высоты окна.
Хотя на этот вопрос был дан ответ, но просто есть другой способ реализовать это поведение, чтобы поделиться с другими.
Создайте глобальную переменную и инициализируйте ее с состоянием по умолчанию вашего BottomSheetBehavior , например
Затем в BottomSheetBehavior.BottomSheetCallback обновите переменную state до текущего состояния
И в BottomSheetBehavior.STATE_DRAGGING , если состояние не раскрыто наполовину,
Установите для состояния BottomSheetBehavior.STATE_HALF_EXPANDED
Это заставит ваш BottomSheet выполнить три шага, то есть свернутый , наполовину расширенный , расширенный .
Надеюсь, это поможет кому-то!
Я пробовал @Massab и @HeyAlex, но не соответствует моему желаемому поведению.
При использовании следующего решения в kotlin, если скольжение нижнего листа находится рядом с расширенным состоянием, оно остается развернутым, если оно находится около половины состояния, остается наполовину, а если оно почти свернуто, оно остается свернутым:
Источник
Hands-on with Material Components for Android: Bottom Sheets
Part 3 of a series covering practical usage of Material Components for Android
This post will be covering the features and API of Bottom Sheet components. To find out how to handle initial setup of Material Components for Android (including the Gradle dependency and creating an app theme), please see my original post:
Setting up a Material Components theme for Android
Attribute by attribute
Bottom Sheets are surface components that hold supplementary screen content. They are anchored to the bottom of a screen (making them ergonomic on mobile/tablet devices) and, similar to Dialogs, are elevated over main screen content. In most cases, they can be expanded/dismissed via a drag up/down gesture.
From a design perspective, there are two types of Bottom Sheets:
- Standard Bottom Sheet: They operate independently to (and allow for simultaneous interaction with) primary screen content. They can be in an expanded, collapsed or hidden state.
- Modal Bottom Sheet: They block primary screen content and must be interacted with or dismissed. A semi-transparent scrim, which can be tapped to dismiss, is displayed behind them to indicate the underlying UI is temporarily inaccessible.
Note: A third type exists: Expanding Bottom Sheet . At the time of writing, the latest release of Material Components for Android is 1.2.0-alpha06 and there is no standard component or class to handle this. A custom implementation could be achieved with something like MotionLayout , but that is outside the scope of this article and won’t be covered.
Basic usage 🏁
Implementing Bottom Sheets is not as simple as using a single component. There exists different classes within Material Components for Android for each type of sheet.
Standard Bottom Sheet
A child View of a CoordinatorLayout can have Standard Bottom Sheet characteristics enabled by using BottomSheetBehavior . In doing so, the bottom anchoring, drag up/down gesture support and animated state transitions and more are handled for us.
This can be done in your screen layout like so:
In the above example, our Bottom Sheet is in fact the FrameLayout . The most important part is that the layout_behavior attribute is set to com.google.android.material.bottomsheet.BottomSheetBehavior . We have also applied some default styling (background shape/tint, elevation, etc.) with the bottomSheetStyle attribute, which will be discussed in more detail below in the “Theming” section.
Modal Bottom Sheet
For Modal Bottom Sheets, the implementation is different. The BottomSheetDialogFragment class (which extends AppCompatDialogFragment ) provides the desired modal behavior in addition to existing DialogFragment functionality.
First of all, a subclass of BottomSheetDialogFragment needs to be created and the onViewCreated callback must be overridden to provide a layout for the contents of the sheet:
Then, inside an AppCompatActivity , the class can be used to show the sheet like so:
It is worth noting that, under the hood, BottomSheetDialogFragment also makes use of BottomSheetBehavior in a BottomSheetDialog class to convert a standard AppCompatDialogFragment to one that has Bottom Sheet characteristics. BottomSheetDialog can be used independently if you don’t want to use a Fragment .
Adjusting behavior ⚙️
There exists a variety of attributes that can be used to adjust the behavior of both Standard and Modal Bottom Sheets. This includes things like “peek” (collapsed) height, hidability, content fitting and more.
Applying attributes
For Standard Bottom Sheets, applying these attributes can be done in XML by applying the attributes to the same child View that has the layout_behavior attribute set to BottomSheetBehavior . In our example above in the “Basic usage” section, this is the FrameLayout .
Alternatively, it can be done programmatically:
For Modal Bottom Sheets there is no XML layout definition for the sheet itself, but we can make use of app-level theme attributes and styles:
Alternatively, it can be done programmatically:
The attributes
Now that we know how to apply attributes, let’s dive into what attributes are available to us.
- behavior_hideable : Determines whether or not the sheet can be hidden when using a drag down gesture (bearing in mind that it can always be hidden programmatically). The default value is false for Standard Bottom Sheets and true for Modal Bottom Sheets.
- behavior_draggable : Determines whether or not the sheet can be collapsed/expanded when using a drag gesture (bearing in mind that a custom way to expand/collapse the sheet will need to be implemented). The default value is true.
- behavior_skipCollapsed : Determines whether or not the collapsed state should be ignored when hiding the sheet. This has no effect if behavior_hideable is not set to true. The default value is false.
- behavior_fitToContents : Determines whether or not the height of the expanded sheet wraps its contents. Alternatively, it expands in two stages: half the height of the parent container, full height of the parent container. The default value is true.
- behavior_halfExpandedRatio : Determines the height of the sheet (as a ratio of the parent container height) when in half-expanded state. This has no effect if behavior_fitToContents is not set to false and should be greater than the peek height. The default value is 0.5 (the recommended ratio in the Material Guidelines).
- behavior_expandedOffset : Determines the offset of the sheet from the top of the parent container when in expanded state. This has no effect if behavior_fitToContents is not set to false and should be greater than the offset when in half-expanded state. The default value is 0dp (the top of the sheet matches the top of the parent container).
- behavior_peekHeight : The initial “peek” (collapsed state) height of the sheet. The default value is auto , which sets the peek height at the 16:9 ratio keyline of the parent container. A dimension (or pixel value, programmatically) can otherwise be used.
A word on modal dismiss animations
You might notice that, for modal bottom sheets (i.e. BottomSheetDialog or BottomSheetDialogFragment ), the animation used when calling dismiss() does not match the normal drag-to-dismiss animation. As of Material Components for Android 1.1.0-alpha10 , there exists an opt-in flag to align these animations:
Setting (and saving) state 💾
The state of a Bottom Sheet can be changed via user interaction, but we can also do so programmatically. By default, these state changes are animated.
Setting state
The following states can be set on a BottomSheetBehavior :
- STATE_EXPANDED : The sheet is fully expanded.
- STATE_COLLAPSED : The sheet is collapsed (“peeking”).
- STATE_HIDDEN : The sheet is hidden and can only be re-shown programmatically.
- STATE_HALF_EXPANDED : The sheet is half-expanded (only applicable if behavior_fitToContents has been set to false).
This can be done like so:
While these should not be set programmatically, a BottomSheetBehavior can also be in one of the following states:
- STATE_DRAGGING : The sheet is being dragged up/down via a gesture.
- STATE_SETTLING : The sheet is animating up/down as a result of programmatically setting its state.
Retaining attribute state on configuration change
We can choose which aspects of state we wish to preserve when the host Activity experiences a configuration change (i.e. the View representing our Bottom Sheet is destroyed and recreated). In this case, “state” refers to the attributes discussed in the “Adjusting behavior” section above.
The following flags can be set (or combined with bitwise OR operations) on a BottomSheetBehavior :
- SAVE_PEEK_HEIGHT : The behavior_peekHeight attribute will be preserved.
- SAVE_FIT_TO_CONTENTS : The behavior_fitToContents attribute will be preserved.
- SAVE_HIDEABLE : The behavior_hideable attribute will be preserved.
- SAVE_SKIP_COLLAPSED : The behavior_skipCollapsed attribute will be preserved.
- SAVE_ALL : All aforementioned attributes will be preserved.
- SAVE_NONE : No attributes will be preserved. This is the default value.
This can be done like so:
There is also a corresponding behavior_saveFlags XML attribute which can be used in layouts and styles.
Listening for state change and slide callbacks 👂
We can listen for changes to Bottom Sheet state as well as the current slide offset. This can be used to coordinate other UI changes, such as fading in/out other View s, adjusting system bar color, etc.
A BottomSheetCallback can be added to a BottomSheetBehavior like so:
In the onStateChanged callback, the newState parameter will be one of the state constants discussed above in the “Setting (and saving) state” section.
In the onSlide callback, the slideOffset parameter is a Float value in the [-1.0, 1.0] range. Hidden state is -1.0, collapsed state is 0.0 and expanded state is 1.0. The value interpolates linearly and increases as the sheet moves upwards.
Note: Multiple callbacks can be added (and removed via BottomSheetBehavior#removeBottomSheetCallback ).
Theming 🎨
Bottom Sheets can be themed in terms of the three Material Theming subsystems: color, typography and shape. For Standard Bottom Sheets, there are no existing style variants but we can create our own. When implementing a global Standard Bottom Sheet style, reference it in your app theme with the bottomSheetStyle attribute. For Modal Bottom Sheets, we have already shown which styles/attributes to use in the “Adjusting behavior” section above. Theming attributes are applicable to both sheet types.
Color
The color of a Bottom Sheet background can be customized with the backgroundTint attribute. This defaults to colorSurface .
Typography
There is no primary text as part of Bottom Sheet components. Text included in the contents of a Bottom Sheet will be styled according to the class/component used as well as the fontFamily app theme attribute.
Shape
The shape of a Bottom Sheet background can be customized with the shapeAppearance attribute. This defaults to shapeAppearanceLargeComponent .
More resources 📚
- The source code for the Playground app used in this article can be found on GitHub.
- Bottom Sheets Design Documentation
- Bottom Sheet API Documentation
- Modal Bottom Sheet API Documentation
I hope this post has provided some insight into Bottom Sheets and how they can be used in your Android app(s). If you have any questions, thoughts or suggestions then I’d love to hear from you!
Источник
Android bottom sheet half expanded
Copy raw contents
Bottom sheets are surfaces containing supplementary content that are anchored to the bottom of the screen.
Contents
Using bottom sheets
Before you can use Material bottom sheets, you need to add a dependency to the Material Components for Android library. For more information, go to the Getting started page.
Standard bottom sheet basic usage:
Modal bottom sheet basic usage:
More information on each individual section, below.
There are several attributes that can be used to adjust the behavior of both standard and modal bottom sheets.
Behavior attributes can be applied to standard bottom sheets in xml by setting them on a child View set to app:layout_behavior , or programmatically:
Behavior attributes can be applied to modal bottom sheets using app-level theme attributes and styles:
More information about these attributes and their default values is available in the behavior attributes section.
Retaining behavior on configuration change
In order to save and restore specific behaviors of the bottom sheet on configuration change, the following flags can be set (or combined with bitwise OR operations):
- SAVE_PEEK_HEIGHT : app:behavior_peekHeight is preserved.
- SAVE_HIDEABLE : app:behavior_hideable is preserved.
- SAVE_SKIP_COLLAPSED : app:behavior_skipCollapsed is preserved.
- SAVE_FIT_TO_CONTENTS : app:behavior_fitToContents is preserved.
- SAVE_ALL : All aforementioned attributes are preserved.
- SAVE_NONE : No attribute is preserved. This is the default value.
Behaviors can also be set in code:
Or in xml using the app:behavior_saveFlags attribute.
Standard and modal bottom sheets have the following states:
- STATE_COLLAPSED : The bottom sheet is visible but only showing its peek height. This state is usually the ‘resting position’ of a bottom sheet, and should have enough height to indicate there is extra content for the user to interact with.
- STATE_EXPANDED : The bottom sheet is visible at its maximum height and it is neither dragging nor settling (see below).
- STATE_HALF_EXPANDED : The bottom sheet is half-expanded (only applicable if behavior_fitToContents has been set to false), and is neither dragging nor settling (see below).
- STATE_HIDDEN : The bottom sheet is no longer visible and can only be re-shown programmatically.
- STATE_DRAGGING : The user is actively dragging the bottom sheet up or down.
- STATE_SETTLING : The bottom sheet is settling to a specific height after a drag/swipe gesture. This will be the peek height, expanded height, or 0, in case the user action caused the bottom sheet to hide.
You can set a state on the bottom sheet:
Note: STATE_SETTLING and STATE_DRAGGING should not be set programmatically.
Listening to state and slide changes
A BottomSheetCallback can be added to a BottomSheetBehavior :
Handling insets and fullscreen
BottomSheetBehavior can automatically handle insets (such as for edge to edge) by specifying any of these to true on the view:
- app:paddingBottomSystemWindowInsets
- app:paddingLeftSystemWindowInsets
- app:paddingRightSystemWindowInsets
- app:paddingTopSystemWindowInsets
On API 21 and above the modal bottom sheet will be rendered fullscreen (edge to edge) if the navigation bar is transparent and app:enableEdgeToEdge is true.
Insets can be added automatically if any of the padding attributes above are set to true in the style, either by updating the style passed to the constructor, or by updating the default style specified by the ?attr/bottomSheetDialogTheme attribute in your theme.
BottomSheetDialog will also add padding to the top when the bottom sheet slides under the status bar, to prevent content from being drawn underneath it.
Making bottom sheets accessible
The contents within a bottom sheet should follow their own accessibility guidelines, such as setting content descriptions for images.
Standard bottom sheet
Standard bottom sheets co-exist with the screen’s main UI region and allow for simultaneously viewing and interacting with both regions. They are commonly used to keep a feature or secondary content visible on screen when content in the main UI region is frequently scrolled or panned.
BottomSheetBehavior is applied to a child of CoordinatorLayout to make that child a persistent bottom sheet, which is a view that comes up from the bottom of the screen, elevated over the main content. It can be dragged vertically to expose more or less content.
API and source code:
Standard bottom sheet example
The following example shows a standard bottom sheet in its collapsed and expanded states:
BottomSheetBehavior works in tandem with CoordinatorLayout to let you display content on a bottom sheet, perform enter/exit animations, respond to dragging/swiping gestures, etc.
Apply the BottomSheetBehavior to a direct child View of CoordinatorLayout :
In this example, the bottom sheet is the FrameLayout .
Modal bottom sheet
Modal bottom sheets present a set of choices while blocking interaction with the rest of the screen. They are an alternative to inline menus and simple dialogs on mobile devices, providing additional room for content, iconography, and actions.
BottomSheetDialogFragment is a thin layer on top of the regular support library Fragment that renders your fragment as a modal bottom sheet, fundamentally acting as a dialog.
Modal bottom sheets render a shadow on the content below them, to indicate that they are modal. If the content outside of the dialog is tapped, the bottom sheet is dismissed. Modal bottom sheets can be dragged vertically and dismissed by sliding them down completely.
API and source code:
Modal bottom sheet example
The following example shows a modal bottom sheet in its collapsed and expanded states:
First, subclass BottomSheetDialogFragment and overwrite onCreateView to provide a layout for the contents of the sheet (in this example, it’s modal_bottom_sheet_content.xml ):
Then, inside an AppCompatActivity , to show the bottom sheet:
BottomSheetDialogFragment is a subclass of AppCompatFragment , which means you need to use Activity.getSupportFragmentManager() .
Note: Don’t call setOnCancelListener or setOnDismissListener on a BottomSheetDialogFragment . You can override onCancel(DialogInterface) or onDismiss(DialogInterface) if necessary.
Anatomy and key properties
Bottom sheets have a sheet, content, and, if modal, a scrim.
- Sheet
- Content
- Scrim (in modal bottom sheets)
Element | Attribute | Related method(s) | Default value |
---|---|---|---|
Color | app:backgroundTint | N/A | ?attr/colorSurface |
Shape | app:shapeAppearance | N/A | ?attr/shapeAppearanceLargeComponent |
Elevation | android:elevation | N/A | 3dp |
Max width | android:maxWidth | setMaxWidth getMaxWidth | 640dp |
Max height | android:maxHeight | setMaxHeight getMaxHeight | N/A |
More info about these attributes and how to use them in the setting behavior section.
Behavior | Related method(s) | Default value |
---|---|---|
app:behavior_peekHeight | setPeekHeight getPeekHeight | auto |
app:behavior_hideable | setHideable isHideable | false for standard true for modal |
app:behavior_skipCollapsed | setSkipCollapsed getSkipCollapsed | false |
app:behavior_fitToContents | setFitToContents isFitToContents | true |
app:behavior_draggable | setDraggable isDraggable | true |
app:behavior_halfExpandedRatio | setHalfExpandedRatio getHalfExpandedRatio | 0.5 |
app:behavior_expandedOffset | setExpandedOffset getExpandedOffset | 0dp |
To save behavior on configuration change:
Attribute | Related method(s) | Default value |
---|---|---|
app:behavior_saveFlags | setSaveFlags getSaveFlags | SAVE_NONE |
Element | Default value |
---|---|
Default style (modal) | @style/Widget.Material3.BottomSheet.Modal |
Default style theme attribute: ?attr/bottomSheetStyle
Element | Theme overlay |
---|---|
Default theme overlay | ThemeOverlay.Material3.BottomSheetDialog |
Default theme overlay attribute: ?attr/bottomSheetDialogTheme
Theming bottom sheets
Bottom sheets support Material Theming, which can customize color and shape.
Bottom sheet theming example
API and source code:
The following example shows a bottom sheet with Material Theming, in its collapsed and expanded states.
Implementing bottom sheet theming
Setting the theme attribute bottomSheetDialogTheme to your custom ThemeOverlay will affect all bottom sheets.
Источник