Radiobutton android studio kotlin

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 и написал простенький пример.

Этот способ намного удобней. Вам даже не нужно объявлять ссылки на переключатели и назначать им слушатели. Код получается более компактным.

Читайте также:  Все телефоны базе android

Обратите внимание, что метод 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):

Готово! Можете запускать проект и проверять работу переключателей.

Источник

RadioButton в Котлине

Радио-кнопка Android — это двухпозиционная кнопка, которая может быть включена или отключена. Кроме того, он работает так же, как флажок, за исключением того, что переключатель не может быть отключен после его выбора.

Как правило, мы используем элементы управления RadioButton, чтобы позволить пользователям выбирать один из нескольких вариантов.

По умолчанию RadioButton находится в состоянии OFF (Unchecked), но мы можем изменить состояние RadioButton по умолчанию с помощью атрибута android: checked .

Следующие шаги для создания нового проекта

  • Нажмите Файл, затем Новый =>Новый проект .
  • Затем установите флажок «Включить поддержку Kotlin» и нажмите кнопку « Далее» .
  • Выберите минимальный SDK, что вам нужно.
  • Выберите « Пустое действие» и нажмите «Готово».

Различные атрибуты виджета RadioButton

XML Attributes Description
android:id Used to uniquely identify the control
android:gravity Used to specify how to align the text like left, right, center, top, etc.
android:checked Used to specify the current state of radio button
android:onClick It’s a name of the method to invoke when the radio button clicked.
android:textSize Used to set size of the text.
android:textColor Used to set color of the text.
android:textStyle Used to set style of the text. For example, bold, italic, bolditalic etc.
android:maxWidth Used to make the view be at most this many pixels wide.
android:minWidth Used to make the view be at least this many pixels wide.
android:background Used to set the background of the radio button control.
android:visibility Used to control the visibility.

Изменить файл strings.xml

Мы можем написать имя приложения как RadioButtonInKotlin и написать другие строки, которые можно использовать.

Добавить RadioButtons в файле activity_main.xml

В Android мы используем радиокнопки внутри RadioGroup, чтобы объединить набор радиокнопок в одну группу, и это гарантирует, что пользователь может выбрать только кнопку из группы кнопок.

Источник

Kotlin Android RadioGroup and RadioButton Tutorial and Example

In this tutorial we want to explore RadioGroup and RadioButton, see how to work with these two.

RadioButton is a compound button and is normally used in conjuction with RadioGroup. Thus checking one RadioButton unchecks the others.

In this tutorial we want to look at some radiobutton examples. These examples are written in either Kotlin or Java. Android Studio is used to build them.

Example 1: Kotlin Android Simple RadioButton Example

This is a simple example written in Kotlin.

Step 1: Dependencies

No special dependencies are needed.

Step 2: Layouts

In your main activity layout, wrap your radiobutton with a radiogroup as follows:

Step 3: Write code

This example comprises only a single activity.

MainActivity.kt

Reference

Download the code below:

No Link
1. Download Code
2. Browse Code
3. Follow Code author

Example 2: RadioButton and RadioGroup Example

Let’s look at an example.

Resoources.

Android platform provides a powerful and flexible way of adding static content as a resource.

These static content will also be packaged into the APK file. The static content will be stored either as a resource or as an asset.

Resources belong to a given type. These types can be:

  1. Drawable.
  2. Layout.
  3. Value.

Let’s start by looking at the layout resources

(a). activity_main.xml

First we will create our activity_main.xml layout. At the root we have a RelativeLayout.

Inside the relativelayout we have our header label, basically a TextView widget which will show our header text.

Then we create a RadioGroup, this RadioGroup will wrap our RadioButtons.

MainActivity.java

Here’s our main activity file. Its deriving from android.app.Activity .

As instance fields we will have a RadioGroup and multiple RadioButtons.

Then we will initialize them using the findViewById() method.

We will then listen to the CheckedChangeListener listener of our radiogroup.

When any RadioButton in our radioGroup is checked, we will first obtain it’s id:

Then we can use the id to to find the actual radiobutton:

Then get it’s value and show in a Toast message:

here’s the full code:

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 .

Источник

RadioButton in Kotlin

Android Radio Button is bi-state button which can either be checked or unchecked. Also, it’s working is same as Checkbox except that radio button can not allow to be unchecked once it was selected.

Generally, we use RadioButton controls to allow users to select one option from multiple options.

By default, the RadioButton in OFF(Unchecked) state but we can change the default state of RadioButton by using android:checked attribute.

Following steps to create new project-

Different attributes of RadioButton widget

XML Attributes Description
android:id Used to uniquely identify the control
android:gravity Used to specify how to align the text like left, right, center, top, etc.
android:checked Used to specify the current state of radio button
android:onClick It’s a name of the method to invoke when the radio button clicked.
android:textSize Used to set size of the text.
android:textColor Used to set color of the text.
android:textStyle Used to set style of the text. For example, bold, italic, bolditalic etc.
android:maxWidth Used to make the view be at most this many pixels wide.
android:minWidth Used to make the view be at least this many pixels wide.
android:background Used to set the background of the radio button control.
android:visibility Used to control the visibility.

Modify the strings.xml file

We can write the name of the application as RadioButtonInKotlin and write other strings which can be used.

Источник

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.

Источник

Читайте также:  Для андроид рабочем столе дата
Оцените статью