Android bottom sheet dialog fragment kotlin

Android BottomSheet Example in Kotlin

The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio.

What is Bottom Sheet?

Bottom Sheet is a component of the Android design support library that is used to display different actions in an expandable UI design. It is an expandable widget that opens from the bottom of the android device on clicking on a specific Button or View.

Types of Bottom Sheet?

There are two different types of Bottom Sheet as

  1. Persistent Bottom Sheet and
  2. Modal Bottom Sheet

1. Persistent Bottom Sheet

A Persistent Bottom Sheet will be displayed on the bottom of the screen in our Android application. This sheet will be displayed at the bottom of the screen making some portion of the content visible. The elevation of this bottom sheet is the same as that of the app. Users can be able to navigate to both the app along with the bottom sheet at a time. Below is the example for the Persistent Bottom Sheet.

2. Modal Bottom Sheet

Modal Bottom Sheet will also be displayed on the bottom of the screen, but the difference is the user will not be able to use the app’s background content when the bottom sheet is open. This type of bottom sheet is having an elevation slightly higher than that of the app. When this bottom sheet is the open user will not be able to access the app’s content. Users can at a time use the bottom sheet or the app’s content. Below is the example for the Modal Bottom Sheet.

What we are going to build in this article?

We will be building a simple application in which we will be displaying the course details in our bottom sheets such as Course Name, Course Duration, Course Tracks, and many more. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Источник

BottomSheetDialogFragment с анимацией при смене состояния и sticky button

Почти каждый андройд разработчик сталкивался с BottomSheetBehavior, но гораздо реже требуется не просто показать BottomSheet, а ещё и добавить анимации, либо пригвоздить какой-то из элементов при раскрытии.
Недавно я столкнулся с такой задачей, реализовал её и решил составить небольшой туториал, который может помочь сэкономить время.

На данной гифке показано, что мы увидим в конце туториала:

Что нужно знать:

Как создать проект и запустить его

Поверхностное понимание что такое BottomSheetDialogFragment и BottomSheetBehavior

Поверхностное понимание что такое LayoutParams

ViewBinding(можно обойтись без него и использовать обычные findViewById)

Читайте также:  Android studio permission denied connect

Первый этап

На первом этапе мы сделаем смену контента в 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

Запустив проект мы увидим следующее:

Полный финальный код

Заключение

Данное решение не претендует на истинно верное.

Вероятно, есть более красивые способы сделать это, я буду рад узнать о таких!

Вы можете экспериментировать с размерами, константами и тд, чтобы подгонять этот подход под вашу ситуацию.

Спасибо за внимание! Буду рад замечаниям и предложениями.

Источник

Android BottomSheet Example in Kotlin

Have you ever seen any BottomSheet in any mobile application? Is this a new term for you? Have you seen this type of UI in Google maps?

And this is called BottomSheet. Now, you can say that you have used this BottomSheet in many applications such as Google Maps, Google Drive, Uber, and many other applications. But it’s time to make a BottomSheet of your own.

Welcome to MindOrks! In this blog, we are going to learn how to implement BottomSheet in Android.

The following is the timeline of this blog:

  • What is BottomSheet?
  • Types of BottomSheet
  • States of BottomSheet
  • Project creation
  • Example of Persistent BottomSheet
  • Example of Modal BottomSheet
  • Conclusion

So, let’s get started.

What is BottomSheet?

A BottomSheet is a component that is used to display some information by sliding the view up from the bottom of the screen and also, you can hide this BottomSheet when the message is conveyed to the users. This is a nice way of conveying some message or performing some task in Android.

Types of BottomSheet

A BottomSheet is of two types:

  • Persistent BottomSheet: The Persistent BottomSheet is visible along with other UI components on the screen. Initially, some content of this Persistent BottomSheet is visible(you can set the peek height i.e. the initial height of BottomSheet to 0 also) and when you slide it up, then rest of the content will appear along with the BottomSheet. The following is an example of Persistent BottomSheet:

NOTE: A Persistent BottomSheet is applied to a child of CoordinatorLayout.

  • Modal BottomSheet: This looks similar to some alert-dialog or some dialog fragment but originating from the bottom of the screen. Unlike Persistent BottomSheet, it is totally invisible initially, and on certain action(maybe a button click), it appears from the bottom of the screen. It generally contains some list of items and the items of the list correspond to some action. The following is an example of Modal BottomSheet:
Читайте также:  Быстро разряжается аккумулятор android

States of BottomSheet

In total, a BottomSheet has five states and with the help of these states, we can perform various actions according to our need.

NOTE: These states are for Persistent BottomSheet

  • STATE_COLLAPSED: This state indicates that the BottomSheet is collapsed i.e. the bottom sheet is visible up to its peek height only.
  • STATE_EXPANDED: This state indicates that the BottomSheet is fully expanded to its maximum height and all the content of the BottomSheet is visible.
  • STATE_DRAGGING: This state indicates that the BottomSheet is dragging either in the upward direction or in the downward direction.
  • STATE_SETTLING: This state indicates that the BottomSheet is settling either to the max height or to the peek height. (Sometimes height can be 0 also when behavior_hideable is set to true )
  • STATE_HIDDEN: This state indicates that the BottomSheet is hidden i.e. it is possible only when the value of behavior_hideable is set to true . Once, the BottomSheet is hidden, you can’t scroll it to make it visible. To make it visible again, you need to change its state by some action(maybe on some button click).

So, these states are important while dealing with a BottomSheet. Now, let’s move on to the example part.

Project Creation

Open Android Studio and create a project with Empty Activity.

Project name: BottomSheetExample

In order to use BottomSheet you need to add the dependency of material design in your app-level build.gradle file. So, add the below line in your build.gradle file and sync the project:

Always use the latest version. (You can find the latest version of the material design from here)

NOTE: Always make sure that the repositories section of build.gradle includes Google’s Maven Repository google()

Here in our example, we will cover both Persistent and Modal BottomSheet. So, we need to make two layout files for both the BottomSheets and a class for Modal BottomSheet. Here is our project structure:

Also, we will be using some string value and dimensions. So, the following is the code for our strings.xml file:

And below is the code for dimens.xml file:

You can hardcode these values.

Now, let’s begin with Persistent BottomSheet.

Example of Persistent BottomSheet

Let’s first make the UI of the Persistent BottomSheet. So, here is the code for layout_persistent_bottom_sheet.xml :

Here, we are having two text views, one for the title and one for the description. Few things that you can notice from the above code is:

The behavior of the layout is set to com.google.android.material.bottomsheet.BottomSheetBehavior

Some flags are set such as:

  • behavior_hideable: This is used to set if the bottom sheet can be hidden totally when we drag it down or not.
  • behavior_peekHeight: This is height up to which the bottom sheet will be visible in the collapsed state.
  • behavior_skipCollapsed: When it is set to true and the bottom sheet is hidable, then it will not have a collapsed state.
Читайте также:  Аккумулятор для подзарядки андроида

After that, we need to add this layout to our activity_main.xml file. Also, as discussed earlier, we will have two buttons on the main page, one for Persistent BottomSheet and other for Modal BottomSheet. So, here is the code for activity_main.xml file:

If you see the above code, then you will find that the BottomSheet is the direct child of the CoordinatorLayout.

Now, if you run the app, then you will see the BottomSheet present on the screen. In order to observe various states of the BottomSheet, you can override the onStateChanged() function in your MainActivity.kt file.

The following is the code of MainActivity:

Here, we have created a variable of BottomSheetBehavior and on click of the button we are changing its state i.e. when it is expanded then we are collapsing it and vice-versa.

Now, run the app and try to observe various states of the BottomSheet.

Example of Modal BottomSheet

The implementation of Modal BottomSheet is similar to that of a fragment or simply a DialogFragment. But here, we use BottomSheetDialogFragment.

So, let’s first make the UI. In this example, we will have three buttons. So, the code for layout_modal_bottom_sheet.xml will be:

Now, we have already made one class named CustomBottomSheetDialogFragment . In this class, we will inflate the layout and handle the button clicks of the Modal BottomSheet. The following is the code for the same:

And finally, we need to call this class from the MainActivtiy on the click of the button. So, the code for this will be:

That’s it. Now, run the app and test both the BottomSheets i.e. the persistent and the modal. You can modify the UI according to your use case.

Conclusion

In this blog, we learned how to implement BottomSheet in our Android Application. We saw the types of BottomSheet that we can implement and finally we saw how to implement both these BottomSheets.

For more info on BottomSheets you can visit the official page.

Hope you enjoyed creating BottomSheet with us.

Do share this blog to spread the knowledge.

Источник

Bottom Sheet Dialog Fragment Using Kotlin

Bottom Sheet Dialog Fragment, is a view that slides from the bottom of a screen to show extra content. In this tutorial we shall be using bottom sheet dialog fragment to display edit text that requires username.

BottomSheetDialogFragment is a class that is provided by default, You will need to create a java class that extends bottom sheet dialog fragment.

In your class override method oncreate, Inside that method you will need to inflate your layout.

Find the views in your layout by calling findview by id.

Here is what our Bottom Sheet Dialog Fragment will contain.

The Bottom Sheet Dialog in this tutorial will contain two elements, Edit Text and Button.

The Edit Text is where users will input Username and Button will Open new Activity when clicked.

If user clicked on continue button within the bottom sheet dialog without providing username a toast with message as inputs required is show.

If user provides username and clicks the continue but a new activity open which contains a TextView to display the the username.

Hence we also learn how to pass data from a fragement to activity.

If you watch the above video and need additional help, Kindly comment below.

For source code, You can get it for only $5 to support the work.

Источник

Оцените статью