- 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
- Kotlin Android CheckBox Tutorial and Example
- CheckBox API Definition
- Important Methods inherited From CompoundButton
- Definition in XML Layout
- Manipulation From Java code.
- Example 1: Kotlin Android CheckBox Example
- Step 1: Dependencies
- Step2: Add to Layout
- Step 3: Write Kotlin Code
- Reference
- Example 2
- Kotlin Android CheckBox Examples
- 1. build.gradle
- 2. activity_main.xml
- 3. MainActivity.java
- Oclemy
- Android CheckBox and Example in Kotlin
- How to Use Checkbox
- Let’s Build a Complete Example of Android Checkbox :
- Output screenshot Android Checkbox example :
- Download source code Android CheckBox in kotlin
- Tutorialwing
- Output
- Getting Started
- Creating New Project
- Setup ViewBinding
- 2. Modify Values Folder
- 3. Modify Layout Folder
- 4. Create Android Checkbox programmatically in Kotlin
- Set Id of Checkbox
- Set Width and 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 of Checkbox
- Set Gravity of Checkbox
- Set Text in Uppercase or Lowercase
- Set Size of Text in Checkbox
- Set Style (Bold/italic) of Text in Checkbox
- Set Letter Spacing of Text in Checkbox
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
Если запустить пример на старом устройстве, то никакой анимации не увидим, но код будет работать без ошибок. На новых устройствах анимация будет работать.
Источник
Kotlin Android CheckBox Tutorial and Example
ep byIn this tutorial you will learn checkbox usage using step by step android examples in either Kotlin or Java.
A checkbox is a specific type of two-states button that can be either checked or unchecked.
Their primary role is to allow a user to select one or more option from a group of alternatives.
CheckBoxes are a popular way of representing Boolean values in Forms. Not only do they get used in mobile applications but also in desktop as well as online forms.
CheckBoxes, unlike RadioButtons, are managed independently of each other. Therefore each must handle its own events.
This is because CheckBoxes, unlike RadioButtons, can be used to select many options, not just one.
A CheckBox is a CompoundButton in that it has two states. Also it does derive from the android.widget.CompoundButton class.
The CompoundButton is an abstract class defined in the android.widget package that acts as the interface definition for a callback to be invoked when the checked state of its child is changed.
The CompoundButton itself is a Button so CheckBox itself will inherit capabilities for Butttons.
CheckBox API Definition
The CheckBox resides in the android.widget namespace.
It derives from android.widget.CompoundButton :
Important Methods inherited From CompoundButton
Here are some of the important properties of CheckBox
Property | Return Type | Description |
---|---|---|
boolean isChecked () | Boolean | Determine if the checkBox is checked or not.Defined in the CompoundButton class. |
void toggle () | void | Change the checked state of the view to the inverse of its current state. Also defined in the CompoundButton class. |
void setChecked (boolean checked) | void | Changes the checked state of this button..Also defined in the CompoundButton class. |
void setOnCheckedChangeListener (CompoundButton.OnCheckedChangeListener listener) | void | Register a callback to be invoked when the checked state of this button changes..Also defined in the CompoundButton class. |
Definition in XML Layout
CheckBoxes can be defined in the XML layouts like most widgets.
Manipulation From Java code.
Then CheckBox can be manipulated from the Java code.
Normally when a CheckBox is selected, the onClick event is raised. So in the above example, we defined an android:onClick attribute of our XML layout then registered it an event handler.
Example 1: Kotlin Android CheckBox Example
This is a simple checkbox example in kotlin android.
Step 1: Dependencies
No special dependency is needed for this project. However Kotlin and androidx are used.
Step2: Add to Layout
Next step is to add checkbox in your main activity layout as follows:
activity_main.xml
Step 3: Write Kotlin Code
The last step is to write kotlin code. Below is the main activity showing how to do it:
MainActivity.kt
Reference
Download the code below:
No | Link |
---|---|
1. | Download Code |
2. | Browse Code |
3. | Follow Code author |
Example 2
Let’s now look at a full example in Java code.
Here’s the XML layout. We add a checkbox here.
Then here’s our java code.
First we specify the package name to host our class.
Then add our imports using the import directive.
Then create a public class we call MainActivity that derives from android.app.Activity .
We will then override the on onCreate() method which is a life cycle callback for android. It gets called when the activity is created.
Fist we invoke the onCreate() method of the super class. That super class is the Activity. We pass it a bundle object.
We invoke the setContentView() which is a method inside the activity class and will inflate our R.layout.activity_main.xml layout and use it as the view for our main activity.
First we reference the CheckBox using the findViewById method, passing in the id from the layout.
We then attach our onCheckedChangeListener to our CheckBox. We override the onCheckedChange() callback.
Inside it we set text depending on whether the checkbox is selected or not.
Kotlin Android CheckBox Examples
In this tutorial we introduce CheckBox, how to use it in android. Our programming language is Kotlin and our IDE is android studio.
Kotlin android checkbox
1. build.gradle
In our app level build.gradle we make sure we have the Kotlin plugin in our dependencies closure.
2. activity_main.xml
We add our CheckBox as well as our header label TextView here.
It is plain old XML for user interfaces even with Kotlin.
3. MainActivity.java
Here’s our MainActivity.kt kotlin code.
That’s it.
Best Regards.
report this ad
Oclemy
Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .
Источник
Android CheckBox and Example in Kotlin
Android CheckBox is used for the android application user interface, where the user can select any one or more options. Checkbox example is the food ordering android app, where the user can select multiple food options. Checkbox control has both option select or deselect (checked and unchecked) option. CompoundButton class is the parent class of the CheckBox class.
You can create a Checkbox in your layout. Checkbox options allow to user select multiple items, so checkbox needs to manage a separately. The checkbox is a type of two state button either unchecked or checked in Android.
How to Use Checkbox
Add the Checkbox in the resource layout file.
Then set onClicklistener on Checkbox like that
Let’s Build a Complete Example of Android Checkbox :
How to When (switch) condition do with kotlin android: for example if you have multiple checkboxes? Let check this example with a simple one and multiple checkboxes in an app.
Step 1. Create new project “ Build Your First Android App in Kotlin “
Step 2. Add below code in “activity_main.xml” resource file
Here 5 checkbox is used, where 4 checkboxes have performed an event, added the android:onClick attribute. And 1 will be use OnClickListener.
Step 3. Open the “MainActivity.kt” and add the following code
Step 4. Now Run the application, in an emulator or On your Android device
Output screenshot Android Checkbox example :
Download source code Android CheckBox in kotlin
Do comment if you have any doubt and suggestion on this tutorial.
Note: This example (Project) is developed in Android Studio 3.1.3. Tested on Android 9 ( Android-P), compile SDK version API 27: Android 8.0 (Oreo)
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.
Источник
Tutorialwing
In this article, we will learn how to create android Checkbox programmatically in Kotlin. We will go through various steps that explains how to create Checkbox and add it in kotlin file, use different attributes to customise it etc. in any android application. For example, how to set text in Checkbox programmatically, how to set id of Checkbox, how to capitalise text of Checkbox dynamically etc. We will get answer to all such questions in this post.
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
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 DynamicCheckbox. Then, fill other required details. |
4. | Then, clicking on Finish button creates new project. |
Newbie in Android ?
Some very important concepts (Recommended to learn before you move ahead)
Before we move ahead, we need to setup for viewBinding to access Checkbox in 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.
Since we have a new project, we will modify the xml and class file to use Checkbox programmatically in kotlin. Please follow the steps below.
2. Modify Values Folder
Open res/values/strings.xml file. Add below code into it.
Other values folders have not been changed. So, we are not going to mention it here.
3. Modify Layout Folder
Open res/layout/activity_main.xml file. Add below code into it.
Note that LinearLayout has id rootLayout. In Kotlin file, we will create Checkbox Dynamically and add it into this LinearLayout having id rootLayout.
4. Create Android Checkbox programmatically in Kotlin
Open src/main/java/com.tutorialwing.dynamiccheckbox/MainActivity.kt file. Then, add below code into it.
Finally, when you run the application, you will get output as shown above.
// Checkbox OUTPUT
Now, Let’s check how to use different attributes of Checkbox to customize it dynamically –
Set Id of Checkbox
Follow steps below to set id of Checkbox programmatically –
- Create ids.xml file in res/values folder. Then, add below code into it –
- Now, we can set id of Checkbox dynamically, in MainActivity.kt file, as –
Here, we have set id of Checkbox using property access syntax – checkBox.id
Set Width and Height of Checkbox
We use layoutParams to set width and height of any View programmatically. In this article, we have added Checkbox in LinearLayout. So, we will define LayoutParams as below –
Here, we have set width and height as WRAP_CONTENT. Some of possible values for width and height are –
- WRAP_CONTENT: Sets value of width or height depending on text inside it.
- MATCH_PARENT: Sets value of width of height depending on width or height of parent layout . i.e. width or height of Checkbox will be same as width or height of parent layout.
- Fixed Value: Sets width or height as per value provided.
Set Padding of Checkbox
Follow steps below to set padding of Checkbox Dynamically –
- If there is no dimens.xml file, create dimens.xml file in res/values folder. Then, add below code in it –
- Now, we can set padding of Checkbox dynamically, in MainActivity.kt file, as –
Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, set padding of Checkbox using setPadding() method.
Set Margin of Checkbox
Follow steps below to set margin of Checkbox Dynamically –
- If there is no dimens.xml file, create dimens.xml file in res/values folder. Then, add below code in it –
- Now, we can set margin of Checkbox dynamically, in MainActivity.kt file, as –
Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, we have defined layoutParams, set margin to layoutParams. After that, set layoutParams to CheckBox.
Set Background of Checkbox
Follow steps below to set background of Checkbox programmatically –
- If there is no colors.xml file, create colors.xml file in res/values folder. Then, add below code in it –
- Now, we can set background of Checkbox dynamically, in MainActivity.kt file, as –
Here, we used setBackgroundColor() method to set background color in checkBox.
Set Visibility of Checkbox
We can set visibility of Checkbox programmatically as –
Here, we have set visibility of Checkbox using checkBox.visibility attribute. Visibility can be of three types – gone, visible and invisible.
Learn to Set Visibility of Checkbox Using XML Attribute
Set Text of Checkbox
Follow steps below to set text of Checkbox programmatically –
- If there is no strings.xml file, create strings.xml file in res/values folder. Then, add below code in it –
- Now, we can set text of Checkbox dynamically, in MainActivity.kt file, as –
Here, we used checkBox.text to set text in checkBox.
Set Color of Text of Checkbox
Follow steps below to set color of text of Checkbox programmatically in Kotlin –
- If there is no colors.xml file, create colors.xml file in res/values folder. Then, add below code in it –
- Now, we can set color of text of Checkbox dynamically, in MainActivity.kt file, as –
Here, we used setTextColor() method to set color of Checkbox of checkBox.
Set Gravity of Checkbox
We can set gravity of text of Checkbox programmatically in Kotlin as –
Here, we have set gravity of Checkbox as center. So, all the text of Checkbox will be center aligned.
We can also apply multiple gravity values as –
Here, we have applied multiple gravity values, in Kotlin, to CheckBox. In above case, text will be aligned as horizontally centered to bottom.
Learn to Set Margin of Checkbox Using XML Attribute
Set Text in Uppercase or Lowercase
Follow steps below to set text in uppercase or lowercase programmatically as –
Set Text in Uppercase
We use checkBox.isAllCaps attributes to set text in uppercase or normal. If it is true, text will be set in uppercase.
In Above case, “Hello Tutorialwing” will be set in Uppercase to CheckBox. So, text will be “HELLO TUTORIALWING”.
By default, isAllCaps is false. So, whatever is written, text will be set as it is. For example,
Above code will set text, “Hello Tutorialwing”, to Checkbox without changing it to Uppercase.
Actually, if isAllCaps is false, text is set as it is. It neither changes to uppercase nor lowercase.
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
Follow steps below to set size of Checkbox programmatically using checkBox.textSize attribute –
- Open res/values/dimens.xml file. Then, add below font-size in it –
- Now, using checkBox.textSize attribute, we can set size of text dynamically as –
Set Style (Bold/italic) of Text in Checkbox
We can set textStyle of Checkbox programmatically as –
In above case, we have set textStyle as bold. So, text of Checkbox will be displayed as bold letters.
If we want to preserve previous textStyle too, we can do it as –
Set Letter Spacing of Text in Checkbox
Follow steps below to set letter spacing of Checkbox programmatically –
- Open res/values/dimens.xml file. Then, add below dimension in it –
- We use checkBox.letterSpacing attribute to set letter spacing of Checkbox as below –
That’s end of tutorial on Checkbox Programmatically in Kotlin With Example.
Источник