- Hands-on with Material Components for Android: Selection Controls
- Part 8 of a series covering practical usage of Material Components for Android
- Setting up a Material Components theme for Android
- Attribute by attribute
- Basic usage 🏁
- Setting and listening for checks 👂
- Grouping Selection Controls 👨👩👧👦
- Theming 🎨
- Color
- Typography
- Shape
- More resources 📚
- Android material design checkbox
- CheckBox (Флажок)
- Отслеживаем смену состояния флажка
- Собственные стили
- Собственный вид
- AnimatedStateListDrawable. Анимация между переключением состояния
- res/drawable/toggle.xml
- res/drawable/toggle_checked.xml
- res/drawable/toggle_unchecked.xml
- res/drawable-v21/toggle.xml
- res/drawable-v21/toggle_unchecked_checked.xml
- res/drawable-v21/toggle_checked_unchecked.xml
- Android material design checkbox
- Android UI Control Checkbox
- Adding Checkbox to UI
- Checkbox Attributes
- Chckbox Styles
- Customizing CheckBox Styles for Application
- Customizing Styles for Individual CheckBox
- Customizing checkbox color
- Checkbox text color
- Customizing checkbox button shape
- Checkbox Listener
- Setting Checkbox State
- Listview Checkbox
- Activity layout
- ListView item layout
- Activity
- ListView Custom Adapter
- About
Hands-on with Material Components for Android: Selection Controls
Part 8 of a series covering practical usage of Material Components for Android
This post will be covering the features and APIs of Radio Button, Checkbox and Switch 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
Selection Controls are small components for scenarios in which users need to select options or toggle settings. They are typically found on settings screens and dialogs.
From a design perspective, there are three main types of selection controls which can be used in different scenarios:
- Radio Buttons: A circular control with two possible states; selected or unselected. Has single-select behavior when in a group of other radio buttons (i.e. Only one control can be selected at a time).
- Checkboxes: A square control with two possible states; checked or unchecked. Has multi-select behavior when in a group of other checkboxes (i.e. Multiple controls can be selected at a time).
- Switches: A control consisting of a thumb and a track. Has two possible states; on or off.
Basic usage 🏁
A MaterialRadioButton , MaterialCheckBox or SwitchMaterial can be included in your layout like so:
Setting and listening for checks 👂
All of the selection controls extend from the base CompoundButton class. As such, they inherit a checkable behavior that can be toggled both programmatically and via touch interaction.
A selection control can be programmatically toggled:
Listening for checked/unchecked state changes is done like so:
Grouping Selection Controls 👨👩👧👦
Selection controls are commonly used in groups. Strictly speaking, any ViewGroup can be used to achieve this (eg. a RecyclerView ). That being said, the RadioGroup class exists to specifically handle single-select behavior for MaterialRadioButton s.
MaterialRadioButton s can be grouped with a RadioGroup like so:
A number of APIs exist for programmatically setting, getting and listening for changes to child MaterialRadioButton checked/unchecked state:
Theming 🎨
Selection controls can be themed in terms of the three Material Theming subsystems: color, typography and shape. When implementing global custom MaterialRadioButton , MaterialCheckBox and SwitchMaterial styles, reference them in your app theme with the radioButtonStyle , checkboxStyle and switchStyle attributes respectively.
Color
The color of selection controls defaults to colorOnSurface (unchecked) and colorControlActivated i.e. colorSecondary (checked) defined in your app theme. In order to override this on a per-control level, you will need to either:
- Use a theme overlay with the above-mentioned color attributes present, applied to the widget with the android:theme attribute.
- Set the useMaterialThemeColors attribute to false and apply a custom tint ColorStateList using CompoundButtonCompat#setButtonTintList .
Typography
The text labels of the selection controls will adopt the fontFamily attribute defined in your app theme. In order to override this in a style or on a per-control level, use the android:textAppearance attribute.
Shape
There are no aspects of any of the selection controls that can be adjusted with shape theming.
More resources 📚
- The source code for the Playground app used in this article can be found on GitHub.
- Selection Controls Design Documentation
- Radio Button API Documentation
- Checkbox API Documentation
- Switch API Documentation
I hope this post has provided some insight into radio buttons, checkboxes and switches 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!
Источник
Android material design checkbox
Selection controls: checkboxes
Selection controls allow the user to select options.
Use checkboxes to:
- Select one or more options from a list
- Present a list containing sub-selections
- Turn an item on or off in a desktop environment
Contents
Before you can use Material checkboxes, you need to add a dependency to the Material Components for Android library. For more information, go to the Getting started page.
Note: is auto-inflated as via MaterialComponentsViewInflater when using a Theme.Material3.* theme.
Making checkboxes accessible
Checkboxes support content labeling for accessibility and are readable by most screen readers, such as TalkBack. Text rendered in check boxes is automatically provided to accessibility services. Additional content labels are usually unnecessary.
A checkbox is a square button with a check to denote its current state. Checkboxes allow the user to select one or more items from a set. Checkboxes can be used to turn an option on or off. Unlike radio buttons, changes in the states of one checkbox do not usually affect other checkboxes.
Note: Checkboxes do not support shape theming and are only rounded square checkboxes.
API and source code:
The following example shows a list of five checkboxes.
Источник
CheckBox (Флажок)
Компонент CheckBox является флажком, с помощью которого пользователь может отметить (поставить галочку) определённую опцию. Очень часто флажки используются в настройках, когда нужно выборочно выбрать определённые пункты, необходимые для комфортной работы пользователю.
Компонент находится в группе Buttons.
Для управления состояниями флажка используйте методы setChecked() или togglе(). Чтобы узнать текущее состояние флажка, вызовите свойство isChecked.
Для экспериментов воспользуемся программой «Счетчик ворон», которую писали при изучении щелчка кнопки.
Как вы помните, в программе была кнопка и текстовое поле. Добавим ещё два элемента CheckBox, а также четыре текстовые метки TextView. Нам нужно постараться, чтобы элементы были аккуратно сгруппированы. Для этой цели воспользуемся вложенными компоновками LinearLayout. Заодно применим интересный приём — мы не будем использовать текст у флажков CheckBox, а воспользуемся текстовыми метками с разными размерами шрифтов. Верхняя метка с крупным шрифтом будет указывать на основную функциональность флажка, а нижняя метка с мелким шрифтом будет использоваться в качестве своеобразной подсказки, в которой содержится дополнительная информация для пользователя.
На самом деле вы можете попробовать другие способы разметки, не воспринимайте как догму. А мы идём дальше. Флажки в нашем приложении нужны для того, чтобы пользователь мог менять вывод текста в текстовом поле. По желанию, можно выводить текст красным цветом и жирным стилем по отдельности или в совокупности. Для этого нам нужно добавить дополнительные строчки кода в обработчик щелчка кнопки.
Запустите проект и попробуйте снимать и ставить галочки у флажков в разных комбинациях, чтобы увидеть, как меняется текст после щелчка кнопки. Код очень простой — проверяется свойство isChecked. Если галочка у флажка установлена, то свойство возвращает true и мы меняем цвет (красный) или стиль текста (жирный). Если флажок не отмечен, то свойство возвращает false, и мы используем стандартные настройки текста.
Отслеживаем смену состояния флажка
С помощью слушателя-интерфейса OnCheckedChangeListener с его методом onCheckedChanged() можно отслеживать смену состояния флажка.
Собственные стили
Если вы используете стандартный проект, то флажок будет использовать цвета Material Design, в частности цвет colorAccent для фона флажка.
В файле res/values/styles.xml добавим строки:
Свойство colorControlNormal отвечает за прямоугольник в невыбранном состоянии, а colorControlActivated за закрашенный прямоугольник в выбранном состоянии.
Присваиваем созданный стиль атрибуту android:theme:
Теперь цвета флажков изменились.
Собственный вид
Если вас не устраивает стандартный вид элементов CheckBox, то не составит никакого труда реализовать свои представления о дизайне.
В папке res/drawable создаём файл checkbox_selector.xml:
Также необходимо подготовить два изображения для двух состояний флажков — выбран и не выбран. В нашем случае это две звезды — серая и жёлтая.
Осталось прописать селектор в компоненте CheckBox (атрибут android:button):
Готово! Можете запускать проект и проверять работу флажков. Ниже код для реагирования на смену состояния флажков:
AnimatedStateListDrawable. Анимация между переключением состояния
Когда мы создали собственный вид флажка, то переключение происходит сразу без анимации. В API 21 появилась возможность установить анимацию при помощи нового класса AnimatedStateListDrawable.
Создадим как прежде файл для собственного вида флажка.
res/drawable/toggle.xml
Далее нужные два значка. Они сделаны в векторном виде.
res/drawable/toggle_checked.xml
res/drawable/toggle_unchecked.xml
Присвоим созданный вид атрибуту android:button.
Код будет работать на устройствах, которые поддерживают векторную графику (API 14), но анимации не будет. Для анимации создадим альтернативный вариант файла в папке res/drawable-v21.
AnimatedStateListDrawable похож на обычный StateListDrawable, но позволяет указать анимацию перехода между двумя состояниями. Мы также указываем две картинки, но также добавляем элементы transition.
res/drawable-v21/toggle.xml
res/drawable-v21/toggle_unchecked_checked.xml
res/drawable-v21/toggle_checked_unchecked.xml
Если запустить пример на старом устройстве, то никакой анимации не увидим, но код будет работать без ошибок. На новых устройствах анимация будет работать.
Источник
Android material design checkbox
Android UI Control Checkbox
September 08, 2017
To capture user selections out of given multiple options or to capture input for fields which have only two states, Checkbox is used. Android Checkbox is a subclass of CompoundButton which intern is a subclass of Button, so it inherits all the attributes from CompoundButton, Button, TextView and View.
Adding Checkbox to UI
You can add Checkbox to android UI by defining CheckBox element in xml manually or using android studio layout design tool which can be accessed by opening layout xml and clicking design tab. Below xml is an example of simple CheckBox definition.
Checkbox Attributes
To define checkbox, main attributes which need to be used are focusable, clickable, textAppearance, textColor, gravity, background, button, and buttonTint. These properties are usually set by device default styles which you can customize to change appearance of checkbox.
Chckbox Styles
Android platform provides styles including material styles for check box. If you set application theme to one of the app compact material themes, Widget.AppCompat.CompoundButton.CheckBox style is applied to checkbox.
Below screen shot shows checkboxes both in checked and unchecked states when application theme is set to Theme.AppCompat.
Customizing CheckBox Styles for Application
You can customize checkbox styles for entire application or specific check box. To change fill colors for all controls including checkbox, you need to set colorAccent to the desired color in your custom app-compact theme that will be applied to your application.
Below are custom app compact theme with colorAccent set to custom color and screen shot showing checkboxes in both states after applying the custom theme to application.
Customizing Styles for Individual CheckBox
To customize individual checkboxes, first create custom theme by inheriting app compact checkbox theme and then apply it to individual checkbox using theme attribute.
Customizing checkbox color
To change checkbox color when it is in unchecked state, you need to set colorControlNormal attribute to the desired color. To change checkbox color when it is in checked state, attribute colorControlActivated needs to be set. You can make checkbox show different color when it is touched or highlighted using colorControlHighlight attribute.
If you want same color applied to checkbox in both states, you can use buttonTint attribute, but the style containing this property needs to be applied to checkbox as style.
Custom checkbox style.
Applying custom style to checkbox.
Checkbox custom style output.
Checkbox text color
To change text color of checkbox text, you can use textColorPrimaryDisableOnly or textColor attribute. If you define textColor style in your custom theme to change checkbox text color, it won’t work if style is applied as theme. You need to apply the custom style to check box using both style and theme in order for check box colors and checkbox text color to be effective. It is better to create two styles one containing check box colors that will be used as theme and second style containing text color for check box text that will be used as style, as shown in the below example. Or you can use textColorPrimaryDisableOnly attribute in custom style and apply it as theme to application or checkbox.
Customizing checkbox button shape
You can customize CheckBox shape by defining drawable as xml in res/drawable folder and setting button attribute of CheckBox to the drawable.
Below is an example of drawable xml definition for CheckBox. It uses cust_chk_select and cust_chk checkbox images for both states, which need to be saved in res/drawable folder.
Using custom drawable in checkbox style.
Custom CheckBox output.
If you need a kind of checkbox that uses colors instead of check mark to indicate whether a checkbox is selected or not, then you can define shapes as xml and use them as drawables as explained below.
Shape with one color saved in res/drawable as my_chk_checked.xml
Second shape with different color saved in res/drawable as my_chk_normal.xml
Selector drawable xml saved in res/drawable as my_chk.xml
Setting the button attribute of checkbox to the selector.
Checkbox Listener
Checkbox event can be handled by setting onClick attribute of Checkbox element in layout xml. To do that, first define a method as shown below and set it as a value for onClick attribute.
Checkbox click event can also be handled by adding on click listener to check box as shown below.
Setting Checkbox State
CheckBox state can be changed using checked attribute in layout xml. By default checkbox is unchecked. You can make it checked by setting checked attribute to true.
You can change the state of checkbox using setChecked method of Checkbox as shown below or you can use toggle method also.
Listview Checkbox
In your app if there are multiple options to be displayed for user selection, then presenting multiple options can be done using ListView and CheckBox. Below example shows how to display checkboxes with ListView by taking ecommerce category search filter as an example.
Activity layout
Activity layout contains ListView.
ListView item layout
ListView item layout is used to display each row of options and it contains TextView and CheckBox
Activity
ListView Custom Adapter
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник