- Android Bottom Sheet / Bottom Sheet Behavior
- BottomSheetDialogFragment с анимацией при смене состояния и sticky button
- Что нужно знать:
- Первый этап
- Второй этап
- Заключение
- Bottom Sheet Above Bottom Navigation
- Bottom Sheet Above Bottom Navigation
- My goal is to place a «bottom sheet» on top of a BottomNavigationView like this: But it stays the following way. Both…
- Introduction
- 1. Modal Bottom Sheet Dialog
- 2. Persistent Bottom Sheet Dialog
- Implementation
- 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 / Bottom Sheet Behavior
Jan 2, 2019 · 4 min read
Android Bottom Sheet is a component that slides up from the bottom of the screen having multiple options. Here are the examples of the Bottom sheet from apps.
There are two types of bottom sheets, Persistent Bottom Sheet and Modal Bottom Sheet.
Persistent Bottom Sheet: This bottom sheet shows in-application content. It will be shown at the base of the screen with a portion of its part noticeable (we can characterize measurements in dp), it shows full substance in the wake of growing it. It has a littler height.
Modal Bottom Sheet: This botom sheet functions as a menu or discourse with choices, it implies this replaces menu or exchange. It has a higher height than the determined base sheet. For the most part, they are utilized for incorporating profound connecting picker activities.
Let’s start to implement the first persistent bottom sheet.
After creating a new project, open build.gradle file in app level, add support design dependency because the bottom sheet is the component of the android design support library.
Create bottom_sheet.xml layout:
Create conent_main.xml layout, that displays on-screen without the bottom sheet.
Now crea t e activity_main.xml including content and bottom sheet layout.
Now code in MainActivity.java
Now lets a look at Modal bottom sheet, the easiest way for the bottom sheet. Modal bottom sheet will be shown as an external dialog using BottomSheetDialog or BottomSheetDialogFragment.
As component we are using (BottomSheetDialog or BottomSheetDialogFragment)is a dialog itself. So its behavior is same as normal dialog, that you can touch outside to dismiss bottom sheet using this method.
We will show the bottom sheet dialog with the same UI that we used before.
That’s it. Now you have learnt the implementation of the bottom sheet. Find code her
Источник
BottomSheetDialogFragment с анимацией при смене состояния и sticky button
Почти каждый андройд разработчик сталкивался с BottomSheetBehavior, но гораздо реже требуется не просто показать BottomSheet, а ещё и добавить анимации, либо пригвоздить какой-то из элементов при раскрытии.
Недавно я столкнулся с такой задачей, реализовал её и решил составить небольшой туториал, который может помочь сэкономить время.
На данной гифке показано, что мы увидим в конце туториала:
Что нужно знать:
Как создать проект и запустить его
Поверхностное понимание что такое BottomSheetDialogFragment и BottomSheetBehavior
Поверхностное понимание что такое LayoutParams
ViewBinding(можно обойтись без него и использовать обычные findViewById)
Первый этап
На первом этапе мы сделаем смену контента в BottomSheetDialogFragment, визуализировав это fading эффектом.
Создадим в папке drawable файл под именем bottom_sheet_background.xml, в котором опишем background для нашего фрагмента, выставив цвет фона и закруглённые углы
Далее опишем стиль для нашего фрагмента в файле styles.xml в папке values
Создадим файл bottom_sheet_layout.xml с разметкой для нашего фрагмента, в комментариях в xml расписано назначение каждого элемента.
В разметке мы имеем одну ViewGroup, которая будет в обоих стейтах и не будет изменяться, и две отдельных ViewGroup для состояний collapsed и expanded.
При вытягивании фрагмента первая будет исчезать и в определённый момент будет заменена второй.
Мы можем перейти к созданию самого фрагмента.
Создадим класс BottomFragment, унаследовав его от BottomSheetDialogFragment
Полный код BottomFragment
Обратим внимание на ключевые моменты
Мы получаем BottomSheetBehavior, выставляем ему peekHeight и вешаем на него слушателя
В методе onSlide() в зависимости от оффсета мы меняем прозрачность наших двух layout и в определённый момент меняем их видимость
Коэффициент 0.5 можно заменить на какой-либо другой и тогда исчезание и появление будет происходить раньше или позже
Вызовем наш фрагмент. Чтобы сделать это быстрее и не добавлять новые кнопки и слушатели, сделаем это прямо из метода onCreate() в MainActivity
Можем запускать наш проект. Мы увидим вот такое поведение:
Второй этап
На данном этапе мы добавим sticky кнопку внизу нашего фрагмента. Для этого мы программно добавим view к нашему экрану.
Сперва создадим layout файл button.xml с кнопкой
Далее программно добавим кнопку к нашему фрагменту, вставив этот код между установкой behavior.state и добавлением коллбека behavior.addBottomSheetCallback
Мы программно надуваем и добавляем наш layout с кнопкой к родительскому layout
Вместо кнопки мы можем начинить наш layout любыми другими view
Запустив проект мы увидим следующее:
Полный финальный код
Заключение
Данное решение не претендует на истинно верное.
Вероятно, есть более красивые способы сделать это, я буду рад узнать о таких!
Вы можете экспериментировать с размерами, константами и тд, чтобы подгонять этот подход под вашу ситуацию.
Спасибо за внимание! Буду рад замечаниям и предложениями.
Источник
Bottom Sheet Above Bottom Navigation
Jun 18, 2019 · 4 min read
Show BottomSheetDialog above the BottomNavigation in android.
🏃 Hello, In this article, we are going to implement BottomSheetDialog above BottomNaviationMenu in android. Many application uses this kind of design to make features easily accessible. As a developer & user, I love BottomSheet design on applications . Let me know in the comment what you think of it. 🎃
Bottom Sheet Above Bottom Navigation
My goal is to place a «bottom sheet» on top of a BottomNavigationView like this: But it stays the following way. Both…
Introduction
Bottom sheets are surfaces containing supple m entary content that is anchored to the bottom of the screen. Bottom sheets can display a wide variety of content and layouts, ranging from menu items (in list and grid layouts) to supplemental content laid out according to the layout grid.
Let’s get started, with the types of bottom sheet dialog we can make in android.
Modal and Persistent dialogs.
1. Modal Bottom Sheet Dialog
Modal bottom sheets have a higher elevation than the app. These usually replace menus or alert dialogs. We can use any layout as a parent layout in this type of dialog. It is similar to custom dialogs, the difference is it shows from the bottom of the screen.
You can find Modal Bottom Sheet Dialog Implementation in the project source.
2. Persistent Bottom Sheet Dialog
Unlike from model bottom sheet, a persistent bottom sheet dialog should be the child of CoordinatorLayout. It displays in-app content. It will be displayed at the bottom of the screen making some portion of the content visible.
NOW, You may have an idea that to implement the bottom sheet above bottom navigation we need a Persistent Bottom Sheet Dialog. To use, it should be a child of the CoordinatorLayout.
Implementation
To implement a Bottom Sheet dialog with Bottom Navigation, you need a material design library. We can use it with/without Navigation Component .
Let’s get our hands dirty 👐 by creating UI for our bottom sheet dialog with TextView & RecyclerView only.
Now, User interface is ready, Let’s include this layout in our MainActivity Layout. Our activity will contain CoordinatorLayout, NavHostFragment, BottomNavigationView inside ConstraintLayout. This part is a bit tricky you can modify/place your view accordingly as you like depending on how you want your UI to look. 😈
Remember to set bottom sheet root layout behavior as.
If you run current code, obviously UI code. Your bottom sheet may not be visible, or it may be hiding somewhere.
Maybe, It is afraid of you? 😮
View is hiding because we didn’t provide bottom sheet peekHeight , set BottomSheetBehavior Peek Height in activity/fragment like.
Here, You can calculate your own peekHeight depending on how much of view you want to display above BottomNavigation.
Usually, It’s a size of actionBarHeight so that view will just peek at you and you can pull your bottom sheet to view the full content.
Источник
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!
Источник