- BottomSheetDialogFragment с анимацией при смене состояния и sticky button
- Что нужно знать:
- Первый этап
- Второй этап
- Заключение
- Bottom Sheet Dialog Fragment in Android
- BottomSheetDialogFragment Demo App
- 1. Create a new project and add material dependencies
- 2. Design Bottom Sheet layout.
- 3. Create a subclass of BottomSheetDialogFragment
- 4. Open the activity XML file and add below code
- 5. Finally, Open the MainActivity and paste below code
- Conclusion
- Android Bottom Sheet / Bottom Sheet Behavior
- Using BottomSheetDialogFragment with Material Design Guideline
- Implementing Bottom Sheet Dialogs using Android Studio
- Types of the Bottom Sheet dialogs
- Modal Bottom Sheet dialog
- Persistent Bottom Sheet dialog
- Implementation
- Implementing a Modal Bottom Sheet dialog
- Preparing layouts
- Initializing the Bottom Sheet in the activity
- Set onClick Listener
- Testing the application
- Implementing a Persistent Bottom Sheet dialog
- Laying out the Bottom Sheet design
- Expanding and collapsing the sheet dialog
- Run the application
- Conclusion
- About the author
- Want to learn more about the EngEd Program?
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 Dialog Fragment in Android
Android material design introduces two types of BottomSheet. Modal Bottom Sheets and Persistent Bottom Sheets. In this post, we’ll learn modal bottom sheets. In other words, you can say we’ll use BottomSheetDialogFragment that renders your fragment as a modal bottom sheet.
Modal Bottom Sheets fundamentally acting as dialog. We can implement it using BottomSheetDialogFragment or BottomSheetDialog. Bottom Sheets evaluation is higher than application. While you touch the outside content of dialog then the bottom sheet is dismissed. Even if dragged vertically it dismissed by completely sliding them down.
BottomSheetDialogFragment Demo App
The final outcome below
In this article, I’m going to create a sample that contains BottomSheetDialogFragment with proper material design guidelines. So let’s get started
1. Create a new project and add material dependencies
2. Design Bottom Sheet layout.
Considering material design guideline, I’m creating a layout file for the bottom sheet. go to res folder and create file named is bottom_sheet.xml
2.1 Update for colors.xml files
2.2 Paste below code in dimens
2.3. Create a new style for bottom sheet button
2.4. At last add strings entry inside strings.xml
3. Create a subclass of BottomSheetDialogFragment
In src folder create a new java file name is ActionBottomDialogFragment which is extending BottomSheetDialogFragment. Apart from this, I’m exposing an interface (callback) that notify the parent activity when one of the buttons is tapped on the Bottom Sheet.
4. Open the activity XML file and add below code
This XML files I’m adding one TextView for displaying callback and Button for showing bottom sheet on button tap
5. Finally, Open the MainActivity and paste below code
Simply, In this activity, I’m showing the Bottom Sheet onClick() event of the button. Now run the application, the final outcome will same as the video.
Conclusion
That’s All! In this android tutorial, we have learned BottomSheetDialogFragment implementation in our app. I hope you enjoyed this article. Help me by sharing this post with all your friends who learning android app development.
Источник
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
Источник
Using BottomSheetDialogFragment with Material Design Guideline
Oct 20, 2017 · 2 min read
As per the material design guideline for BottomSheet, there are two types of BottomSheets:
- Modal bottom sheets: It Can be implemented using BottomSheetDialog or BottomSheetDialogFragment. Elevation is higher than the app. It is fundamentally acting as the dialog.
- Persistent bottom sheets: It can be implemented using BottomSheetBehavior in conjunction with a CoordinatorLayout.
In this article, we are going to learn how to implement the BottomSheetDialogFragment to use the bottom sheet as a modal dialog.
So lets get started…
Step 1: Create the layout file for bottom sheet (consider the material design guideline while building the guideline):
Step 2: Create the dimen.xml file:
The dp used while creating the bottom sheet layout are adhere to the Material Design Guidelines .
Step 3: The string.xml file:
Step 4: Create the custom BottomSheetDialogFragment
Step 5: To show the dialog fragment in the activity:
That’s it. Now you can run the application and check the BottomSheet in your application.
You can create the custom callback (interfaces) in the custom bottom sheet dialog fragment to notify the activity when one of the button is tapped on the Bottom Sheet (dialog fragment).
Источник
Implementing Bottom Sheet Dialogs using Android Studio
February 19, 2021
Bottom Sheet dialogs seem to be replacing regular Android dialogs and menus. The Bottom Sheet is a component that slides up from the bottom of the screen to showcase additional content in your application.
A Bottom Sheet dialog is like a message box triggered by the user’s actions. Companies such as Google, Facebook, and Twitter have implemented this feature in their applications.
Bottom Sheet dialogs are used in music, payment, and file management applications. In terms of application, any Android view including TextView , ImageView , RecyclerViews , Buttons , and Text inputs can be included in a Bottom Sheet. This makes it quite dynamic.
For instance, it can help display data retrieved from a database. A Bottom Sheet can be applied in many instances as long as it fits your application cycle.
Types of the Bottom Sheet dialogs
The two main types of Bottom Sheets are Modal and Persistent dialogs;
Modal Bottom Sheet dialog
It has similar characteristics as an Alert dialog. When triggered (by the user’s action), it slides up from the bottom of the current screen. A Modal Sheet can contain a list of items.
These elements can correspond to some action when clicked. The Modal Bottom Sheet blocks interaction with the rest of the screen to indicate a shift of focus. It is dismissed when the user clicks outside the view or on back press.
Instead of wrapping the Modal Bottom Sheet with the CoordinatorLayout like the persistent dialog, we create it dynamically, just like a regular dialog.
An excellent example of a Modal Bottom Sheet dialog is the Google Drive application.
Or this payment Bottom Sheet dialog example.
.
Modal Bottom Sheets are an excellent alternative to inline menus and simple dialogs. They provide additional room for more content, iconography, and more screen actions.
Persistent Bottom Sheet dialog
Persistent Bottom Sheet dialogs provide supplementary content about the current screen. It is as a child of the CoordinatorLayout .
A portion of the container is visible to provide users with more content. Unlike the Modal dialog, a Persistent Bottom Sheet widget is permanent for the current screen content.
Here is an example of a Persistent Bottom Sheet dialog in a Google Maps application.
Implementation
Create a new Android studio project. To implement a Bottom Sheet dialog, you need a material design library.
Include the following library in your app.gradle file.
Sync the project to download the library. This will make all the required functions available in your project.
We will discuss how to implement the two types of Bottom Sheet dialogs using Android studio.
Implementing a Modal Bottom Sheet dialog
Preparing layouts
To show the dialog, you need an XML file that arranges the dialog’s content. You can choose to use any widgets that fit in the dialog. The views can include RecyclerView , ImageViews , Text , Inputs , and Button .
Make sure you generate some vector images as showcased in the ImageView of the below XML file. Or check this GitHub repository for more reference.
Here is the bottom_sheet_dialog_layout.xml layout that I will be using to implement a Modal Bottom Sheet.
A dialog is triggered by a specified user action. In this tutorial, we will include a button and trigger the dialog using it’s onClick Listener.
Go ahead and add a button in your activity_main.xml file.
Initializing the Bottom Sheet in the activity
Initialize the button and set the onClick Listener inside the onCreate function. When the button is clicked, we will show the dialog. Create a function showBottomSheetDialog() and call it inside the button’s onClick Listener, as shown below.
Inside the showBottomSheetDialog() function, initialize the Bottom Sheet dialog. Initialize the bottom_sheet_dialog_layout.xml using the setContentView method.
Declare all the views and call them by id as specified in the Bottom Sheet layout. Finally, we will diplay the dialog using bottomSheetDialog.show() .
Run the app to test if the Bottom Sheet is working. Clicking the button should trigger the dialog to slide from the bottom to the top.
Set onClick Listener
Each element in the dialog layout can be assigned an action. When an item is clicked, it will redirect the user as specified in the code.
In our application, we will show a Toast message when an element is clicked. You can make modifications in your future apps to direct users to different activities.
Add the following OnClickListeners right above bottomSheetDialog.show() .
We use bottomSheetDialog.dismiss() to close the dialog once an element is clicked.
You can also set a more distinct action, instructing your application to do something when the dialog is dismissed. For instance, the app can launch a new activity.
Testing the application
- BottomSheetDialogFragment A fragment can be displayed as a Bottom Sheet dialog. Go ahead and create a new fragment, call it BottomSheetFragment . You can opt to start a new project.
Creating a new fragment will generate an XML file associated with it. Go ahead and include your layout design in it. Use the same layout as specified in bottom_sheet_dialog_layout.xml . Inflate the layout for this fragment, as shown below.
Add a button in the activity_main.xml , declare it, and set OnClick Listener as dicussed in the previous steps.
We want to open the fragment when the button is clicked.
Indicate the following code block inside the button’s OnClick Listener.
We need to convert the fragment to a Bottom Sheet. We do so by extending BottomSheetDialogFragment rather than Fragment .
When you run the application, it should show the dialog shown below.
Check the code used to implement both Modal dialogs on GitHub.
Implementing a Persistent Bottom Sheet dialog
Laying out the Bottom Sheet design
We will use an example of a simple login screen. Instead of showing it within the regular activity layout, we will use a Persistent dialog to slide it into the main screen.
I have created a bottom_sheet_dialog_layout.xml file and included the following simple login layout.
This is not a Bottom Sheet yet. It’s just a regular layout. To transform the layout to a Bottom Sheet dialog, a few declarations should be added to the root layout.
These statements will control the Bottom Sheet’s behaviors. You can learn more about these attributes from here.
The Bottom Sheet behavioral flags include;
app:layout_behavior — applies the BottomSheetBehavior into the XML file. This is assigned to com.google.android.material.bottomsheet . It is the most important BottomSheetBehavior attribute since it defines a given layout as a Bottom Sheet dialog.
app:behavior_hideable — takes a Boolean value. If true , a user can drag and hide the dialog by sliding it down. If false, the dialog will float on the screen and will not be hideable.
app:behavior_peekHeight — it defines the height of the Bottom Sheet visible to the user.
Remember to add an id to be used to access the layout.
For a Bottom Sheet to be implemented effectively, it must be a child of CoordinatorLayout . To do that, go to your main XML file. This could be an Activity or Fragment. In our case, it will be the activity_main.xml .
Here is the code to do that.
Remember to include the Bottom Sheet we designed. Wrap it with CoordinatorLayout .
Expanding and collapsing the sheet dialog
To control the sliding and collapsing of the dialog, we use states. The Bottom Sheet has several states which you need to understand. They include:
- STATE_EXPANDED — the dialog is visible to its maximum defined height.
- STATE_COLLAPSED — the dialog is visible depending on the set peekHeight .
- STATE_DRAGGING — the user is dragging the dialog up and down.
- STATE_SETTLING — show that the dialog is settling at a specific height. This can be the peekHeight , expanded height, or zero if the dialog is hidden.
- STATE_HIDDEN — the dialog is not visible.
The last thing we will do is listen to the state of the dialog. We use BottomSheetCallback to detect any state changes.
Declare the following parameters:
Initialize the behavior Bottom Sheet layout and the arrow image:
We will assign OnClick Listener to the arrow vector image. When clicked, we want to expand or collapse the dialog.
Implement a BottomSheetCallback to listen to the BottomSheetBehavior state.
onStateChanged tells the application what’s happening on the dialog depending on the state. onSlide will rotate the arrow image (while sliding bottom to top) until the STATE_EXPANDED has reached its maximum height.
On the other side, the image will rotate to its original state when STATE_COLLAPSED is at peekHeight .
Run the application
Check the code used to implement the Persistent dialog on GitHub.
Conclusion
The Bottom Sheet dialog is a unique way to display menus and dialogs. It provides more room to include content. Bottom Sheet dialogs can accomodate different components.
Check out Material documentation to learn more about the Bottom Sheet dialog.
Peer Review Contributions by Wanja Mike
About the author
Joseph Chege is an undergraduate student taking a Bachelor in Business Information Technology, a 4th-year student at Dedan Kimathi University of Technology. Joseph is fluent in Android Mobile Application Development and has a lot of passion for back-end development.
Want to learn more about the EngEd Program?
Discover Section’s community-generated pool of resources from the next generation of engineers.
Источник