- TextInputLayout Styling
- Hint color
- Label, Helper and Error
- Fonts
- Spaces
- Bottom line color
- Box background-color
- Cursor and Selection
- Android: выдвигающийся экран снизу
- Зависимости
- Создание макетов
- Container view
- Динамическое управление
- Прикрепление элементов к нижнему экрану
- Скрытие плавающей кнопки при скроле
- Android Bottom Sheet / Bottom Sheet Behavior
- 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
- BottomSheetDialogFragment с анимацией при смене состояния и sticky button
- Что нужно знать:
- Первый этап
- Второй этап
- Заключение
TextInputLayout Styling
Today, with the material components, we have at least 3 out of box implementations of input layout: Default, FilledBox, and OutlinedBox. And we want to briefly walk through their styling:
If you are looking for a brief solution you can use this table. Below you can find the description of each of these parameters in detail.
Hint color
Hint color could be set via “android:textColorHint” parameter of TextInputLayout. This parameter also changes the label default color (label focused color could also be changed in other ways). Let’s set a purple color (#673AB7) as an example.
Label, Helper and Error
Such parameters as “app:hintTextAppearance”, “app:helperTextTextAppearance” and “app:errorTextAppearance” together with all the necessary text parameters of styles.xml should be used to customize labels, helpers and errors in TextInputLayout. The parent of the text appearance style should be TextAppearance.AppCompat or some of its children.
Also, please keep in mind the following:
- “ app:hintTextAppearance” affects the focused label color and label size in any state;
- when an error is shown, the bottom/border line will have the color indicated in the “android:textColor” parameter of errorTextAppearance. This color will be changed to the default once the error is removed.
Here is the TextAppearances for error and helper that was used in the above shown TextInputLayouts:
Fonts
Fonts of all elements except inputted text (label, hint, error, and helper) could be easily changed in the program via the typeface parameter of TextInputLayout. We have done it in the following way:
Spaces
Label’s, Helper’s and Error’s spaces are connected to the EditText in the TextInputLayout. So, to increase or decrease spaces between the error/helper messages and bottom line/border you should use “android:layout_marginBottom” parameter, between the label and the top of the text, or add some space on the start of the error, helper and the label, and you should set positive or negative padding to the EditText. But you should understand that this will affect the text inside the InputLayout so, it would be better if horizontal spaces were symmetric from both sides.
As an example, let’s increase space above the errors for Default and OutlinedBox input layouts and decrease for FilledBox input layout. Also, let’s add some extra space at the start of the input layouts.
Bottom line color
Bottom line color could be changed with “app:backgroundTint” attribute of EditText view. Pay attention to the prefix, “app:” that makes this parameter back-compatible and useful even for Android API 16.
As for the OutlinedBox, it does not have the bottom line but has an outline instead. To change its color we should use “app:boxStrokeColor” parameter, but this parameter changes stroke color in the focused state only. Changing the default state of the stroke is a bit tricky. We should override mtrl_textinput_default_box_stroke_color color. The line below should be added to the color.xml file:
Let’s make the bottom line and the outline stroke color purple (#673AB7) as well.
Box background-color
This element is present in Filled and Outlined input layouts and can be changed via “app:boxBackgroundColor” parameter. Let’s change this parameter to the transparent purple (#26673AB7) only for FilledBox input layout.
Cursor and Selection
Finally, we get to the most interesting part — how to change the cursor and the selection handles. Most of you have already tried to use “app:textSelectHandle” parameters, that allow changing the drawable of the cursor handle and selection left and right handles. But how to change the color without drawing custom drawables and without changing the main application colors? It is not the secret that the cursor and handles color, as well as label color in focus mode, take their color from the AppTheme “colorAccent”. Of course, we can change it for the whole project but it is not obligatory. We can just use ThemeOverlay and change the “colorAccent” for a single view. We should inherit our style from ThemeOverlay.AppCompat and set it as the “android:theme” parameter of the view and that is all. As for the selection highlight, you can change it via android:textColorHighlight of the EditText.
In the example above was used android:color/holo_blue_light:
So, my final layout looked like this:
colors.xml includes the following colors:
styles.xml includes the following styles:
Tap the 👏 button if you found this article useful!
About the Author
Dmytro is Android Developer at OmiSoft, whose inner perfectionist does not allow to be content with mediocre results but forces him to move forward to excellence.
Need an Android mobile app with clean & maintainable code? Click here to get an estimate! Or find us on Facebook and Twitter.
Источник
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.
Теперь плавающая кнопка закреплена в верхнем углу нашего нижнего экрана и перемещается вместе с ним.
Скрытие плавающей кнопки при скроле
Для скрытия кнопки при скроле необходимо добавить слушатель к нижнему экрану и отображать/скрывать кнопку. Для начала найдем необходимые вью:
Для скрытия кнопки в момент начала скрола и отображения после полного сворачивания нижнего экрана, используйте следующее:
Результат обоих вариантов можно увидеть ниже:
Источник
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
Источник
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.
Источник
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
Запустив проект мы увидим следующее:
Полный финальный код
Заключение
Данное решение не претендует на истинно верное.
Вероятно, есть более красивые способы сделать это, я буду рад узнать о таких!
Вы можете экспериментировать с размерами, константами и тд, чтобы подгонять этот подход под вашу ситуацию.
Спасибо за внимание! Буду рад замечаниям и предложениями.
Источник