- RadioButton и RadioGroup
- Методы
- Программное добавление переключателя
- Добавление картинок к переключателю
- Пример с переключателями
- Слушатель OnCheckedChangeListener
- Метод clearCheck()
- Метод getCheckedRadioButtonId(): Узнать выбранный элемент
- Кот или муж?
- Собственные стили
- Собственный вид
- Android RadioButton & RadioGroup with Example in Kotlin
- Using RadioButton
- Radio button selected by default.
- Let’s Build a Complete Example of Android Checkbox :
- Output screenshot Android RadioButton example :
- Download source code Android RadioButton in kotlin
- Android RadioButton, RadioGroup Using Kotlin
- Android Tutorial
- Kotlin Tutorial
- Android RadioButton
- Project Structure
- Layout Code
- Activity Code
- Tutorialwing
- Output
- Getting Started
- Creating New Project
- Setup ViewBinding
- 2. Modify Values Folder
- 3. Modify Layout Folder
- 4. Create Android Radio Group programmatically in Kotlin
- Set Id of Radio Group
- Set Width and Height of Radio Group
- Set Padding of Radio Group
- Set Margin of Radio Group
- Set Background of Radio Group
- Set Visibility of Radio Group
- Set Text of Radio Group
- Set Color of Text of Radio Group
- Set Gravity of Radio Group
- Set Text in Uppercase or Lowercase
- Set Size of Text in Radio Group
- Set Style (Bold/italic) of Text in Radio Group
- Set Letter Spacing of Text in Radio Group
RadioButton и RadioGroup
Познакомимся с компонентом RadioButton, который находится в разделе Buttons. Главная особенность элемента состоит в том, что он не используется в одиночестве. Всегда должно быть два и более переключателя и только один из них может быть выбранным. Это похоже на кнопки на старых радиоприёмниках, когда нажимая на одну из кнопок, вы заставляете отключиться другую нажатую кнопку.
Компоненты RadioButton (переключатель) используются в составе контейнера RadioGroup. Обратите внимание на два момента. Первое — в контейнер RadioGroup можно включать не только RadioButton, но и другие элементы, например, TextView. Второе — переключатели работают в своём контейнере, т.е. если у вас два контейнера RadioGroup, то переключатели из одного контейнера не влияют на поведение переключателей второго контейнера.
Методы
Основным методом для переключателя является toggle(), который инвертирует состояние переключателя. Также представляют интерес методы isChecked(), который возвращает состояние кнопки, и setChecked(), изменяющий состояние кнопки в зависимости от параметра.
Для уведомления о переходе положения переключателя в активное или неактивное состояние в результате определённых событий, нужно вызывать метод setOnCheckedChangeListener() с применением слушателя OnCheckedChangeListener.
Программное добавление переключателя
Получив ссылку на группу переключателей, можно добавить в неё ещё один переключатель (или другой элемент управления) через метод addView():
Добавление картинок к переключателю
Вы можете добавить изображение в левой, правой, верхней и нижней части переключателя, используя либо определённые атрибуты XML или программно.
Через атрибут drawableRight и ему подобных:
Программно через метод setCompoundDrawables(left, top, right, bottom):
В этом примере мы указали только одно значение для правого края, остальным присвоили значение null. Можно одновременно задействовать все стороны переключателя.
Пример с переключателями
Создадим новую форму с четырьмя кнопками-переключателями, с помощью которых будем заливать фон приложения выбранным цветом. Сначала подготовим строковые ресурсы.
Создадим простейшую разметку на основе LinearLayout. Заполним форму текстовым блоком определённого цвета и присвоим ему текст «Текущий цвет». В нижней части формы расположим четыре цветных текстовых блока, а под ними четыре переключателя, с помощью которых мы будем менять цвет основного текстового блока.
Обратите внимание, что элементы RadioButton помещаются в контейнер RadioGroup. Если теперь посмотреть на форму, то увидим одно большое серое поле. А снизу расположились в ряд четыре метки, а ещё ниже также в ряд расположились четыре переключателя. Причём последний серый переключатель имеет выбранный статус (android:checked=»true»).
Переходим к программной части. Добавляем слушатель для обработки щелчков на кнопках-переключателях.
Запустим приложение и посмотрим, что у нас получилось. Пощёлкаем по переключателям и убеждаемся, что всё работает.
Слушатель OnCheckedChangeListener
Показанный выше способ использует щелчок, так как переключатели можно рассматривать как кнопки. Но на самом деле у переключателей есть свой слушатель OnCheckedChangeListener. Я расположил в новом проекте RadioGroup с тремя RadioButton и написал простенький пример.
Этот способ намного удобней. Вам даже не нужно объявлять ссылки на переключатели и назначать им слушатели. Код получается более компактным.
Обратите внимание, что метод onCheckedChanged() принимает параметр RadioGroup, что позволяет применять один и тот же слушатель OnCheckedChangeListener() для нескольких групп переключателей. Вариант -1 сработает, когда группа переключателей будет сброшена в коде с помощью метода clearCheck().
Метод clearCheck()
Когда пользователь выберет любой из переключателей, то он уже не сможет снять с него отметку. Какой-нибудь из переключателей обязательно будет выбран в одном контейнере с ним. Единственный способ очистить все переключатели — программно вызвать метод clearCheck(), который относится к классу RadioGroup.
Метод getCheckedRadioButtonId(): Узнать выбранный элемент
У RadioGroup есть также метод getCheckedRadioButtonId(), который позволяет узнать идентификатор выбранного переключателя. Можем узнать выбранный переключатель через нажатие кнопки.
Также можно узнать индекс выбранного переключателя через метод indexOfChild():
Кот или муж?
Теперь, когда вы познакомились с новым элементом, то вам не составит труда написать программу для нелёгкого выбора.
Девушки, нужен ли вам такой муж? Если он не любит котиков, то будет ли любить вас? Возьмите лучше котёнка. Он клёвый.
Собственные стили
Если вы используете стандартный проект, то переключатели будут использовать цвета Material Design, в частности цвет colorAccent для кружочка с точкой.
В файле res/values/styles.xml добавим строки:
Свойство colorControlNormal отвечает за окружность в невыбранном состоянии, а colorControlActivated за точку и окружность в выбранном состоянии.
Присваиваем созданный стиль атрибуту android:theme:
Теперь цвета флажков изменились.
Собственный вид
Если вас не устраивает стандартный вид элементов RadioButton, то не составит никакого труда реализовать свои представления о дизайне.
В папке res/drawable создаём файл radiobutton_selector.xml:
Также необходимо подготовить два изображения для двух состояний — выбран и не выбран.
Осталось прописать селектор в элементе RadioButton при размещении на экране (атрибут android:button):
Готово! Можете запускать проект и проверять работу переключателей.
Источник
Android RadioButton & RadioGroup with Example in Kotlin
Android RadioButton is given a choice to users to select an option. It can be shown side by side or in other ways but it takes space on the screen. Another option is use spinner, if there is so many (like 4-30 or more) option and space on the screen are less.
Radio Buttons are mutually exclusive ( One RadioButton is not influenced or caused by another RadioButtons), you have to group them together using a RadioGroup. By grouping – The System will ensure that only one Radio button selects in a group.
You can add RadioButton in resource file or dynamically create in class file.
RadioButton has 2 states – checked or unchecked. By default Radio Buttons are unchecked, User can check it by simply touch (Click) on it. Once a RadiaButton is checked by the user it can’t be unchecked by simply click on it. It will uncheck RadioButton only within the same RadioGroup.
Using RadioButton
Add the RadioButton in resource layout file.
Then set onClicklistener on RadioButton , check below code. (Note : code is in kotlin)
Radio button selected by default.
To make a radio button is selected by default, put android:checked=»true» within the RadioButton element.
Let’s Build a Complete Example of Android Checkbox :
Example: what if you have multiple RadioButton? Let check this example with simple one and multiple RadioButton in a 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 7 checkbox is used, where 6 checkbox is perform a event , added the android:onClick attribute. And 1 will be use OnClickListener.
Step 3. Open the “MainActivity.kt” and add following code
Step 4. Now Run the application, in emulator or On you android device
Output screenshot Android RadioButton example :
Download source code Android RadioButton 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.
Источник
Android RadioButton, RadioGroup Using Kotlin
Android Tutorial
Kotlin Tutorial
In this tutorial, we’ll be discussing and implementing RadioButton and RadioGroups in our Android Application using Kotlin.
Android RadioButton
A RadioButton is a widget which can be set to checked or an unchecked state. Once a RadioButton is checked you cannot uncheck it unless it’s present inside a RadioGroup.
A RadioGroup is a container that holds RadioButtons. At a time inside a RadioGroup, only one RadioButton can be set as checked.
A RadioButton is defined in the xml in the following manner:
android:text is used to set the text of the RadioButton.
You can set the text gravity using the android:gravity attribute
android:onClick is used to set the function in the Kotlin activity to be triggered when the RadioButton is clicked.
android:buttonTint is used to set the color of the circular button. By default, it is set to the colorAccent specified in the styles.xml.
To define a RadioButton programmatically we use:
A RadioGroup is defined in the following way in the XML.
Setting the orientation on the RadioGroup would lay the RadioButtons in that order(horizontally/vertically).
To define a RadioGroup programmatically, we do:
This adds a single RadioButton inside the RadioGroup.
A RadioGroup can set Layout Weights similar to a LinearLayout.
We use the attribute android:weightSum on the RadioGroup and android:layout_weight on the RadioButton(s).
To clear ALL states from a RadioGroup we need to invoke the following in our Kotlin Activity class.
RadioGroup Listener
In our activity, we can use the RadioGroup.OnCheckChangedListener interface callback to listen for changes in the states of the RadioButtons held inside the RadioGroup .
radioGroup argument is the current radiogroup and i is the id of the RadioButton present in that RadioGroup.
In the following section, we’ll be creating a Single View Application that hosts RadioGroups from the XML as well as programmatically. We’ll display a Toast whenever any of the RadioButtons is checked.
Project Structure
Layout Code
The code for the activity_main.xml layout is given below:
Activity Code
The code for the MainActivity.kt class is given below:
In the above code, we’ve created a Second RadioGroup which holds the RadioButtons horizontally.
We’ve implemented RadioGroup.OnCheckedChangeListener interface on our Activity.
androidlyRadioButton is triggered when the single RadioButton defined in the layout gets checked.
We need to typecast it from View to RadioButton.
fun onCheckedChanged(group: RadioGroup?, checkId: Int) is what gets triggered everytime a RadioButton from any of the RadioGroups gets checked or unchecked.
checkedRadioButtonId property is used to get the ID of the RadioButton that was selected.
We use the isChecked property on the RadioButton to display a Toast only when a RadioButton gets checked.
The output of the above application in action is given below:
This brings an end to this tutorial. You can download the AndroidlyRadioButtons Project from the link below.
Источник
Tutorialwing
In this article, we will learn how to create android Radio Group programmatically in Kotlin. We will go through various steps that explains how to create Radio Group and add it in kotlin file, use different attributes to customise it etc. in any android application. For example, how to set text in Radio Group programmatically, how to set id of Radio Group, how to capitalise text of Radio Group dynamically etc. We will get answer to all such questions in this post.
Output
Tutorialwing Android Dynamic Radio Group Output
Tutorialwing Android Dynamic Radio Group Output
Getting Started
We can define android Radio Group widget as below –
Radio Group is used to create a multiple-exclusion scope for a set of radio buttons i.e. You can select only one radio button out of all radio buttons present in any radio group. Selecting one radio button automatically de-select previously selected radio button.
Now, how do we use Radio Group 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 DynamicRadioGroup. 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 Radio Group 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 Radio Group programmatically in kotlin. Please follow the steps below.
2. Modify Values Folder
Open res/values/strings.xml file. Add below code into it.
Then, create new file ids.xml in res/values folder. Then, add below cdoe 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 Radio Group Dynamically and add it into this LinearLayout having id rootLayout.
4. Create Android Radio Group programmatically in Kotlin
Open src/main/java/com.tutorialwing.dynamicradiogroup/MainActivity.kt file. Then, add below code into it.
Finally, when you run the application, you will get output as shown above.
Tutorialwing Android Dynamic Radio Group Output
Tutorialwing Android Dynamic Radio Group Output
Now, Let’s check how to use different attributes of Radio Group to customize it dynamically –
Set Id of Radio Group
Follow steps below to set id of Radio Group programmatically –
- Create ids.xml file in res/values folder. Then, add below code into it –
- Now, we can set id of Radio Group dynamically, in MainActivity.kt file, as –
Here, we have set id of Radio Group using property access syntax – radioGroup.id
Set Width and Height of Radio Group
We use layoutParams to set width and height of any View programmatically. In this article, we have added Radio Group 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 Radio Group will be same as width or height of parent layout.
- Fixed Value: Sets width or height as per value provided.
Set Padding of Radio Group
Follow steps below to set padding of Radio Group 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 Radio Group dynamically, in MainActivity.kt file, as –
Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, set padding of Radio Group using setPadding() method.
Set Margin of Radio Group
Follow steps below to set margin of Radio Group 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 Radio Group 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 Radio Group.
Set Background of Radio Group
Follow steps below to set background of Radio Group 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 Radio Group dynamically, in MainActivity.kt file, as –
Here, we used setBackgroundColor() method to set background color in radioGroup.
Set Visibility of Radio Group
We can set visibility of Radio Group programmatically as –
Here, we have set visibility of Radio Group using radioGroup.visibility attribute. Visibility can be of three types – gone, visible and invisible.
Learn to Set Visibility of Radio Group Using XML Attribute
Set Text of Radio Group
Follow steps below to set text of Radio Group 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 Radio Group dynamically, in MainActivity.kt file, as –
Here, we used radioGroup.text to set text in radioGroup.
Set Color of Text of Radio Group
Follow steps below to set color of text of Radio Group 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 Radio Group dynamically, in MainActivity.kt file, as –
Here, we used setTextColor() method to set color of Radio Group of radioGroup.
Set Gravity of Radio Group
We can set gravity of text of Radio Group programmatically in Kotlin as –
Here, we have set gravity of Radio Group as center. So, all the text of Radio Group will be center aligned.
We can also apply multiple gravity values as –
Here, we have applied multiple gravity values, in Kotlin, to Radio Group. In above case, text will be aligned as horizontally centered to bottom.
Learn to Set Margin of Radio Group 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 radioGroup.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 Radio Group. 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 Radio Group 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 radioGroup.
Set Size of Text in Radio Group
Follow steps below to set size of Radio Group programmatically using radioGroup.textSize attribute –
- Open res/values/dimens.xml file. Then, add below font-size in it –
- Now, using radioGroup.textSize attribute, we can set size of text dynamically as –
Set Style (Bold/italic) of Text in Radio Group
We can set textStyle of Radio Group programmatically as –
In above case, we have set textStyle as bold. So, text of Radio Group 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 Radio Group
Follow steps below to set letter spacing of Radio Group programmatically –
- Open res/values/dimens.xml file. Then, add below dimension in it –
- We use radioGroup.letterSpacing attribute to set letter spacing of Radio Group as below –
That’s end of tutorial on Radio Group Programmatically in Kotlin With Example.
Источник