- 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
- Урок 20. Android Data Binding. Обработка событий
- Ссылка на метод
- Вызов метода
- Tutorialwing
- Output
- Getting Started
- Creating New Project
- Setup ViewBinding
- Using CheckBox in Kotlin
- Different Attributes of CheckBox in XML
- Set Id of CheckBox
- Set Width of CheckBox
- Set Height of CheckBox
- Set Padding of CheckBox
- Set Margin of CheckBox
- Set Background of CheckBox
- Set Visibility of CheckBox
- Set Text of CheckBox
- Set Color of Text in CheckBox
- Set Gravity of CheckBox
- Set Text in Uppercase, Lowercase
- Set text in uppercase
- How do we set text in lowercase?
- Set Size of Text in CheckBox
- Set Style (Bold/italic) of Text in CheckBox
- Set Letter Spacing of Text in CheckBox
- Set Typeface of Text in CheckBox
- Set fontFamily of Text in CheckBox
- Different Attributes of Android CheckBox Widget
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
Если запустить пример на старом устройстве, то никакой анимации не увидим, но код будет работать без ошибок. На новых устройствах анимация будет работать.
Источник
Урок 20. Android Data Binding. Обработка событий
В этом уроке рассмотрим как обрабатывать события View.
Полный список уроков курса:
С помощью биндинга мы можем вешать обработчики на события View. Есть два способа это сделать, давайте рассмотрим их.
Ссылка на метод
Рассмотрим пример с onClick. Допустим, у нас на экране, который отображает данные по работнику (Employee), есть кнопка Delete и мы хотим присвоить ей onClick обработчик.
Создаем свой класс обработчик:
Он не обязательно должен наследовать OnClickListener. Но его метод должен быть public и иметь те же параметры, что и метод OnClickListener.onClick(View view), т.е. должен быть один параметр типа View. Имя метода может быть любым.
Прописываем этот обработчик, как variable в layout.
В onClick кнопки ссылаемся на его метод onDelete:
Осталось создать объект MyHandler и передать его в биндинг:
По нажатию на кнопку Delete будет вызван метод onDelete объекта myHandler.
Если при попытке настроить обработчик в биндинге вы получаете подобную ошибку:
Listener class android.view.View.OnClickListener with method onClick did not match signature of any method handler::onDelete
внимательно проверьте, что модификаторы доступа и параметры метода в вашем обработчике такие же, что и в методе интерфейса стандартного обработчика. В случае с onClick — это OnClickListener.
Вызов метода
Если в первом способе мы просто указывали биндингу, какой метод обработчика вызвать, то во втором способе мы просто сами будем вызывать этот метод. Этот способ более гибкий, т.к. метод нашего обработчика не обязан иметь те же параметры, что и метод интерфейса стандартного обработчика.
Рассмотрим снова пример с onClick. Создаем обработчик.
В метод onDelete мы планируем получать не View, как в примере раньше, а объект Employee.
MyHandler так же, как и ранее, прописываем в variable и передаем в binding.
В onClick кнопки пишем вызов
Здесь используетcя лямбда. На вход нам предлагаются те же параметры, что и в методе интерфейса стандартного обработчика, т.е. view из OnClickListener.onClick(View view). Но мы не используем этот параметр. В метод onDelete мы передаем employee, который у нас описан, как один из variable в layout.
В результате по нажатию на кнопку, биндинг предоставит нам View, на которое было нажатие. Но мы его проигнорируем, возьмем у биндинга объект Employee и отправим в handler.onDelete.
Биндинг дает нам возможность не писать параметры в лямбде, если они нам не нужны. Т.е. можно сделать так:
Таким образом биндинг поймет, что его View нам не нужно, и не будет его передавать. Имейте ввиду, что если в стандартном обработчике несколько параметров, то вы можете указать либо все параметры, либо ни одного.
Чтобы закрепить тему, давайте рассмотрим пример с CheckBox. Например, на экране с данными по работнику есть чекбокс Enabled, который включает/выключает работника.
В обработчике создаем метод,
Будем получать объект Employee и состояние чекбокса.
В onCheckedChanged пишем вызов метода нашего обработчика.
В лямбде указываем параметры, которые пришли бы нам в стандартном обработчике OnCheckedChangeListener.onCheckedChanged(CompoundButton compoundButton, boolean checked).
Параметр view нам не понадобится, а вот checked передаем в метод вместе с employee.
Теперь по нажатию на чекбокс, биндинг будет вызывать метод onEnabled и передавать туда Employee объект и состояние чекбокса.
Рассмотрим еще несколько интересных моментов.
При вызове обработчика мы можем использовать условия.
Например, есть такой обработчик.
Мы можем в layout указать его методы следующим образом
Т.е. если чекбокс включен, то вызываем метод onEnabled, иначе — onDisabled.
Если в одном из случаев нам ничего не надо вызывать, то можно использовать void
В биндиге по умолчанию есть переменная context, которую вы всегда можете использовать, если есть необходимость.
Значение переменной context получено вызовом метода getContext у корневого View вашего layout.
В этих примерах я создавал отдельный объект обработчика, но разумеется вы можете создавать интерфейсы. прописывать их в качестве variable в layout и использовать хоть само Activity в качестве реализации.
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Tutorialwing
In this article, we will learn about android CheckBox using Kotlin. We will go through various example that demonstrates how to use different attributes of CheckBox.
In this article, we will get answer to questions like –
- What is CheckBox?
- Why should we consider CheckBox while designing ui for any app?
- What are possibilities using CheckBox while designing ui? etc.
Let’s have a quick demo of things we want to cover in this tutorial –
Output
Tutorialwing Android Kotlin checkbox Output
Tutorialwing Android Kotlin checkbox Output
Getting Started
We can define android CheckBox widget as below –
A checkbox is a specific type of two-states button that can be either checked or unchecked.
Now, how do we use CheckBox in android application ?
Creating New Project
At first, we will create an application.
So, follow steps below to create any android project in Kotlin –
Step | Description |
---|---|
1. | Open Android Studio (Ignore if already done). |
2. | Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next. |
3. | In next screen, select project name as CheckBoxUsingKotlin. Then, fill other required details. |
4. | Then, clicking on Finish button creates new project. |
Some very important concepts (Recommended to learn before you move ahead)
Before we move ahead, we need to setup for viewBinding to access Android CheckBox Using Kotlin file without using findViewById() method.
Setup ViewBinding
Add viewBinding true in app/build.gradle file.
Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.
Now, we can access view in Kotlin file without using findViewById() method.
Using CheckBox in Kotlin
Follow steps below to use CheckBox in newly created project –
- Open res/layout/activity_main.xml file. Then, add below code in it –
- We can also access it in Kotlin File, MainActivity.kt, as below –
Now, run the application. We will get output as below –
Tutorialwing Android Kotlin checkbox Output
Tutorialwing Android Kotlin checkbox Output
Different Attributes of CheckBox in XML
Now, we will see how to use different attributes of Android CheckBox using Kotlin to customise it –
Set Id of CheckBox
Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of CheckBox using android:id attribute like below –
Here, we have set id of CheckBox as checkbox_ID using android:id=”” attribute. So, if we need to reference this CheckBox, we need to use this id – checkbox_ID.
Learn to Set ID of CheckBox Dynamically
Set Width of CheckBox
We use android:layout_width=”” attribute to set width of CheckBox.
We can do it as below –
Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of CheckBox Dynamically
Set Height of CheckBox
We use android:layout_height=”” attribute to set height of CheckBox.
We can do it as below –
Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of CheckBox Dynamically
Set Padding of CheckBox
We use android:padding=”” attribute to set padding of CheckBox.
We can do it as below –
Here, we have set padding of 10dp in CheckBox using android:padding=”” attribute.
Learn to Set Padding of CheckBox Dynamically
Set Margin of CheckBox
We use android:layout_margin=”” attribute to set margin of CheckBox.
We can do it as below –
Here, we have set margin of 10dp in CheckBox using android:layout_margin=”” attribute.
Learn to Set Margin of CheckBox Dynamically
Set Background of CheckBox
We use android:background=”” attribute to set background of CheckBox.
We can do it as below –
Here, we have set background of color #ff0000 in CheckBox using android:background=”” attribute.
Learn to Set Background of CheckBox Dynamically
Set Visibility of CheckBox
We use android:visibility=”” attribute to set visibility of CheckBox.
We can do it as below –
Here, we have set visibility of CheckBox using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of CheckBox Dynamically
Set Text of CheckBox
We use android:text=”” attribute to set text of CheckBox.
We can do it as below –
Here, we have set text (“Hello Tutorialwing”) in CheckBox using android:text=”” attribute.
Similarly, we can set any text using this attribute.
Learn to Set Text of CheckBox Dynamically
Set Color of Text in CheckBox
We use android:textColor=”” attribute to set color of text in CheckBox.
We can do it as below –
Here, we have set color (#ffffff i.e. white) of text (“Hello Tutorialwing”) in CheckBox using android:textColor=”” attribute. Similarly, we can set any color using this attribute.
Learn to Set Color of CheckBox Dynamically
Set Gravity of CheckBox
We use android:gravity=”” attribute to set gravity of text in CheckBox.
We can do it as below –
Here, we have set gravity of text in CheckBox using android:gravity=”” attribute. Attribute value can be – “center_horizontal”, “center”, “center_vertical” etc.
Learn to Set Gravity of CheckBox Dynamically
Set Text in Uppercase, Lowercase
If we need to show text of CheckBox in uppercase or lowercase etc.
Set text in uppercase
We can use android:textAllCaps=”true” attribute to set text in uppercase. We can do it as below –
Attribute android:textAllCaps=”true” sets text in uppercase. So, HELLO TUTORIALWING is set in CheckBox.
By default, false is set in this attribute. So, Whatever value is written in android:text=”” attribute, it will be set as it is. For example,
Above code will set Hello Tutorialwing to CheckBox.
How do we set text in lowercase?
- In xml file – write all the text in lowercase.
- In kotlin file – take text as string. Then, convert it in lowercase. Then, set it to CheckBox.
Set Size of Text in CheckBox
We use android:textSize=”” attribute to set size of text in CheckBox.
We can do it as below –
Here, we have set size of text in CheckBox using android:textSize=”” attribute.
Learn to Set Size of Text of CheckBox Dynamically
Set Style (Bold/italic) of Text in CheckBox
We use android:textStyle=”” attribute to set style (bold, italic etc.) of text in CheckBox.
We can do it as below –
Here, we have set style of text in CheckBox using android:textStyle=”” attribute. This attribute can take bold, italic or normal.
Learn to Set Style of Text of CheckBox Dynamically
Set Letter Spacing of Text in CheckBox
We use android:letterSpacing=”” attribute to set spacing between letters of text in CheckBox.
We can do it as below –
Here, we have set spacing between letters of text in CheckBox using android:letterSpacing=”” attribute.
Learn to Set Letter Spacing of Text of CheckBox Dynamically
Set Typeface of Text in CheckBox
We use android:typeface=”” attribute to set typeface in CheckBox.
We can do it as below –
Here, we have set typeface of text in CheckBox using android:typeface=”” attribute. This attribute can take values – “sans”, “normal”, “monospace” or “normal”.
Learn to Set Typeface of CheckBox Dynamically
Set fontFamily of Text in CheckBox
We use android:fontFamily=”” attribute to set fontFamily of text in CheckBox.
We can do it as below –
Here, we have set fontFamily (Here, sans-serif) of text in CheckBox using android:fontFamily=”sans-serif” attribute.
Till now, we have see how to use android CheckBox using Kotlin. We have also gone through different attributes of CheckBox to perform certain task. Let’s have a look at list of such attributes and it’s related task.
Different Attributes of Android CheckBox Widget
Below are the various attributes that are used to customise android CheckBox Widget. However, you can check the complete list of attributes of CheckBox in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –
Attributes of checkbox are inherited from Textview, Compound Button and View. Some of the attributes inherited from Textview are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:ems | Makes view exactly this ems wide. |
2 | android:gravity | It specifies how the text inside the view be aligned. E.g. right, left ,center etc. |
3 | android:height | Sets height of the view. |
4 | android:maxWidth | Sets maximum allowed width of the view. |
5 | android:minWidth | Sets minimum allowed width of the view. |
6 | android:width | Sets width of the view |
Attributes of Checkbox inherited from Compound Button are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:button | Sets drawable for button graphic. |
2 | android:buttonTint | Sets tint to button graphic. |
3 | android:buttonTintMode | Blending mode used to apply the button graphic tint. |
Attributes of Checkbox inherited from View are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:id | It sets unique identifier for view. |
2 | android:padding | Sets padding of view. |
3 | android:onClick | Defines the operations to perform when this view is clicked |
4 | android:visibility | Sets the visibility (visible, gone etc.) of the Checkbox. |
5 | android:tooltipText | Text to be shown in popup when cursor is hovered on view. |
6 | android:background | Sets background to view. |
7 | android:alpha | Sets alpha in view. |
We have seen different attributes of CheckBox and how to use it. If you wish to visit post to learn more about it
Thus, we have seen what is CheckBox, how can we use android CheckBox using Kotlin ? etc. We also went through different attributes of android CheckBox.
Источник