- Android: выдвигающийся экран снизу
- Зависимости
- Создание макетов
- Container view
- Динамическое управление
- Прикрепление элементов к нижнему экрану
- Скрытие плавающей кнопки при скроле
- BottomSheetBehavior
- Summary
- Nested classes
- XML attributes
- Constants
- Public constructors
- Public methods
- Bottom Sheet Android Tutorial – Working with BottomSheet
- Types of Bottom Sheet
- #1 Persistent Bottom Sheet
- #2 Modal Bottom Sheets
- Bottom Sheets – Material Components for Android
- Types of Bottom Sheets
- Persistent bottom sheets
- Modal Bottom Sheets
- Persistent bottom sheets with example
- attributes
- Setting bottom sheets attributes programmatically
- Bottom sheets states:
- Handling bottom sheets callbacks
- Modal Bottom Sheets with example
- Showing a modal bottom sheets
- Conclusion
Android: выдвигающийся экран снизу
Данная статья является переводом статьи Emrullah Luleci, а также её продолжения.
Нижний экран (Здесь и далее под «нижним экраном/слоем» будет подразумеваться элемент bottom sheet — прим. пер.) — компонент, выезжающий снизу экрана, который используется для отображения дополнительного контента. Подробнее об этом элементе можно узнать на официальной сайте посвященном материальному дизайну.
Зависимости
Для использования этого элемента, добавьте последние версии библиотек поддержки в свой проект:
Создайте класс наследник от AppCompatActivity:
Создание макетов
Содержимое нижнего экрана
Для удобства воспользуемся макетами. Назовем файл с нижним слоем bottom_sheet.xml.
behavior_peekHeight: Определяет высоту видимой части.
behavior_hideable: Определяет, может ли нижний экран скрываться свайпом вниз.
Container view
Создайте CoordinatorLayout в качестве корневого вью. Добавьте в него прямым наследником bottom_sheet.xml. Элементы app_bar и activity_bottom_sheet_content не имеют прямого отношения к нижнему экрану, поэтому их можно заменить или удалить.
На данном этапе нижний экран должен работать примерно так:
Динамическое управление
Поведением и свойствами нижнего экрана можно также управлять динамически с помощью Java.
Прикрепление элементов к нижнему экрану
Также можно прикрепить вью к нижнему экрану, чтобы прикрепленный элемент перемещался одновременно с нижним слоем.
Добавим Floating Action Button в макет созданный выше. Новый компонент должен являться непосредственным наследником CoordinatorLayout также как и bottom_sheet. Для прикрепления элемента к нижнему экрану необходимо добавить app:layout_anchor с id вью нижнего экрана, а также app:layout_anchorGravity со значением top|end.
Теперь плавающая кнопка закреплена в верхнем углу нашего нижнего экрана и перемещается вместе с ним.
Скрытие плавающей кнопки при скроле
Для скрытия кнопки при скроле необходимо добавить слушатель к нижнему экрану и отображать/скрывать кнопку. Для начала найдем необходимые вью:
Для скрытия кнопки в момент начала скрола и отображения после полного сворачивания нижнего экрана, используйте следующее:
Результат обоих вариантов можно увидеть ниже:
Источник
BottomSheetBehavior
public class BottomSheetBehavior
extends Behavior
java.lang.Object | ||
↳ | androidx.coordinatorlayout.widget.CoordinatorLayout.Behavior | |
↳ | com.google.android.material.bottomsheet.BottomSheetBehavior |
An interaction behavior plugin for a child view of CoordinatorLayout to make it work as a bottom sheet.
To send useful accessibility events, set a title on bottom sheets that are windows or are window-like. For BottomSheetDialog use AppCompatDialog.setTitle(int) , and for BottomSheetDialogFragment use ViewCompat.setAccessibilityPaneTitle(View, CharSequence) .
Summary
Nested classes
Callback for monitoring events about bottom sheets.
State persisted across instances
XML attributes
Constants
Peek at the 16:9 ratio keyline of its parent.
This flag will preserve all aforementioned values on configuration change.
This flag will preserve the fitToContents boolean value on configuration change.
This flag will preserve the hideable boolean value on configuration change.
This flag will not preserve the aforementioned values set at runtime if the view is destroyed and recreated.
This flag will preserve the peekHeight int value on configuration change.
This flag will preserve the skipCollapsed boolean value on configuration change.
The bottom sheet is collapsed.
The bottom sheet is dragging.
The bottom sheet is expanded.
The bottom sheet is half-expanded (used when mFitToContents is false).
The bottom sheet is hidden.
The bottom sheet is settling.
Public constructors
Public methodsAdds a callback to be notified of bottom sheet events. | |
---|---|
static BottomSheetBehavior | from(V view) A utility function to get the BottomSheetBehavior associated with the view . Returns the current expanded offset. Gets the ratio for the height of the BottomSheet in the STATE_HALF_EXPANDED state. Returns the bottom sheet’s maximum width, or -1 if no maximum width is set. Gets the height of the bottom sheet when it is collapsed. Returns the save flags. Sets whether this bottom sheet should skip the collapsed state when it is being hidden after it is expanded once. Gets the current state of the bottom sheet. |
boolean | isDraggable() |
boolean | isFitToContents() |
boolean | isGestureInsetBottomIgnored() Returns whether this bottom sheet should adjust it’s position based on the system gesture area. Gets whether this bottom sheet can hide when it is swiped down. |
void | onAttachedToLayoutParams(CoordinatorLayout.LayoutParams layoutParams) |
void | onDetachedFromLayoutParams() |
boolean | onInterceptTouchEvent(CoordinatorLayout parent, V child, MotionEvent event) |
boolean | onLayoutChild(CoordinatorLayout parent, V child, int layoutDirection) |
boolean | onNestedPreFling(CoordinatorLayout coordinatorLayout, V child, View target, float velocityX, float velocityY) |
void | onNestedPreScroll(CoordinatorLayout coordinatorLayout, V child, View target, int dx, int dy, int[] consumed, int type) |
void | onNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type, int[] consumed) |
void | onRestoreInstanceState(CoordinatorLayout parent, V child, Parcelable state) |
Parcelable | onSaveInstanceState(CoordinatorLayout parent, V child) |
boolean | onStartNestedScroll(CoordinatorLayout coordinatorLayout, V child, View directTargetChild, View target, int axes, int type) |
void | onStopNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target, int type) |
boolean | onTouchEvent(CoordinatorLayout parent, V child, MotionEvent event) |
void | removeBottomSheetCallback(BottomSheetBehavior.BottomSheetCallback callback) Removes a previously added callback. |
void | setBottomSheetCallback(BottomSheetBehavior.BottomSheetCallback callback) |
void | setDraggable(boolean draggable) Sets whether this bottom sheet is can be collapsed/expanded by dragging. |
void | setExpandedOffset(int offset) Determines the top offset of the BottomSheet in the STATE_EXPANDED state when fitsToContent is false. |
void | setFitToContents(boolean fitToContents) Sets whether the height of the expanded sheet is determined by the height of its contents, or if it is expanded in two stages (half the height of the parent container, full height of parent container). |
void | setGestureInsetBottomIgnored(boolean gestureInsetBottomIgnored) Sets whether this bottom sheet should adjust it’s position based on the system gesture area on Android Q and above. |
void | setHalfExpandedRatio(float ratio) Determines the height of the BottomSheet in the STATE_HALF_EXPANDED state. |
void | setHideable(boolean hideable) Sets whether this bottom sheet can hide when it is swiped down. |
void | setMaxWidth(int maxWidth) Sets the maximum width of the bottom sheet. |
final void | setPeekHeight(int peekHeight, boolean animate) Sets the height of the bottom sheet when it is collapsed while optionally animating between the old height and the new height. |
void | setPeekHeight(int peekHeight) Sets the height of the bottom sheet when it is collapsed. |
void | setSaveFlags(int flags) Sets save flags to be preserved in bottomsheet on configuration change. |
void | setSkipCollapsed(boolean skipCollapsed) Sets whether this bottom sheet should skip the collapsed state when it is being hidden after it is expanded once. |
void | setState(int state) Sets the state of the bottom sheet. |
void | setUpdateImportantForAccessibilityOnSiblings(boolean updateImportantForAccessibilityOnSiblings) Sets whether the BottomSheet should update the accessibility status of its CoordinatorLayout siblings when expanded. Источник Bottom Sheet Android Tutorial – Working with BottomSheetHave you seen the Bottom Sheet Android Component? It slides up from the Bottom to display some more options to the user. I am pretty sure that you have already seen Bottom Sheet in Google Maps application. You can also use the Bottom Sheet in your application. And if you want to use it in your app, in this post, I will guide you about integrating the android Bottom sheet in your project. You can also go through the official guide about the Bottom Sheet . Types of Bottom Sheet#1 Persistent Bottom SheetAs clear from the name, it is persistent at the bottom of the screen. A user can view the full Bottom Sheet by dragging the sheet up vertically. The Bottom Sheet is slightly elevated, and it can display more options or app content to the user. For example, the picture that we saw above is an example of a persistent bottom sheet. #2 Modal Bottom SheetsAgain as the name suggests, these sheets behave like Modals or dialogues. It shadows the activity or fragment when activated. And if we tap outside the Bottom Sheet, it is dismissed just like a modal. A user can also slide up and slide down to activate and deactivate the Bottom Sheet, respectively. I hope you got that what exactly is the android bottom sheet and when we can use it in our application. Now let’s learn how we can implement it in an Android Studio Project. Источник Bottom Sheets – Material Components for AndroidAndroid Bottom Sheet is the Android Materiel Design Components which slides up from the bottom of the screen. Also, part of the material design components. Bottom sheets are displayed as a result of the user-triggered action, and also it can reveal additional content by swiping up. Already, I have explained some of the material components in detail. check below, Table of Contents Types of Bottom SheetsThere are two types of Bottom Sheets available in android: Persistent bottom sheetsBottomSheetBehavior is applied to a child of CoordinatorLayout to make that child a persistent bottom sheet. The Persistent bottom sheets display in-app content. It will be displayed at the bottom of the screen making some portion of the content visible. Modal Bottom Sheetsslides up from the bottom of the screen to reveal more content. It’s a dialog which are alternatives to content choosers, simple menus, or dialog. Used to present deep-linked content from other apps. Lets see both bottom sheets in details. This is my example demo using bottom sheets in android. Persistent bottom sheets with exampleAs mentioned above, the bottom sheets part of the android material design library. Make sure you have included the library in your project. BottomSheetBehavioris a type of layout_behavior used for persistent bottom sheets. It requires setting CoordinatorLayout as the root element of that layout. Adding the xml attribute app:layout_behavior:android.support.design.widget.BottomSheetBehavior to the child view. attributesbehavior_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. behavior_hideable — Determines whether or not the sheet can be hidden when using a drag-down gesture. 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. 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. Setting bottom sheets attributes programmaticallyBottom sheets states:Bottom sheets have 5 states, STATE_EXPANDED — The bottom sheet is visible and its maximum height and it is neither dragging nor settling (see below). STATE_DRAGGING — Sheet can be collapsed/expanded when using a drag gesture. 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. STATE_HIDDEN — The bottom sheet is no longer visible. STATE_HALF_EXPANDED — The sheet is half-expanded (only applicable if behavior_fitToContents has been set to false). changing the bottom sheets state programatically, Handling bottom sheets callbacksIn the onStateChanged callback, the newState parameter will be the current state of the bottom sheets. In the onSlide callback, the slideOffset parameter is a Float value in the [-1.0, 1.0] range. The hidden state is -1.0, the collapsed state is 0.0 and the expanded state is 1.0. The value interpolates linearly and increases as the sheet moves upwards. Modal Bottom Sheets with exampleModal Bottom Sheets are not part of the view layout like Persistent sheets. Instead, they will be shown dynamically using BottomSheetDialog or BottomSheetDialogFragment. Before creating our BottomSheetDialogFragment however, let’s create the layout for the dialog. layout_modal_bottomsheet.xml design for this xml: I am using recyclerview to display all the items in the bottom sheets dialog fragment. I have explained recyclerview in details in my another post. We need to create a class that inherits from BottomSheetDialogFragment. Lets create MyBottomSheetDialogFragment with recyclerview. Showing a modal bottom sheetsTo show a modal bottom sheet, create MyBottomSheetDialogFragment instance and call the show() method on that class. Note that we did not set the behavior for the modal sheet to be hideable, nor did we set the peek height. The modal bottom sheet automatically computes appropriate values for both peek height and expanded height. You can download this example on GITHUB. ConclusionThanks for reading. Please share if you like it. Also, don’t forget to share your feedback on comments. Источник |