Radio group button in android

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

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

Читайте также:  All android versions list with names

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

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

Источник

Radio Group Button setOnCheckedChangeListener Java Android

This is how you can implement setOnCheckedChangeListener and create radio button groups in Java Android Studio:

You have some problem with radio group, you can new to Android development so now you will have much idea to how can handle it.

Android Radio Button Group and radioGroup.setOnCheckedChangeListener in JAVA ANDROID

In this article, we are going to learn how to work with setOnCheckedChangeListener method for radio buttons in android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Create Empty Project

How to implement on Android — setOnCheckedChangeListener for Radio Buttons in android programmatically

S tep 2 — “Add the following code to res/layout/activity_main.xml.“

I worked in simple relative layout method for only give basic example.

*In the below code, we have declared RadioGroup as ”@+id/radioButton1” and ”@+id/radioButton2”.. and then ”@+id/radioButton6”.

RELATIVE LAYOUT FILE CODE IN XML:

Step 3: MainActivity.java” java file − Add the following code to src/MainActivity.java

The following examples show how to use android.widget.RadioButton#setOnCheckedChangeListener() . These examples are extracted from open source projects

JAVA CODE IN MAIN ACTIVITY:

Review Application

In this tutorial we are simply adding setOnCheckedChangeListener() click event on radio group. With this app developer can easily do multiple type of task when each radio button is clicked or not. So here is the complete step by step tutorial for Add setOnCheckedChangeListener to radiogroup in android.

Step 4: Results and How to Work SEEK BAR Codes!

android java — RadioGroup and RadioButton example

Читайте также:  Взлом touchgrind bmx андроид

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:

In this lesson, you learnt Best Java code snippets using radioGroup.setOnCheckedChangeListener in java. import android.widget.RadioGroup;

How to use android.widget.RadioGroup in Android !

W hat is Radio Button

Interface definition for a callback to be invoked when the checked radio button changed in this group.

RadioGroup.OnCheckedChangeListener study finished.

If you have any question write comments I will reply.

Thanks for reading my blog.

Have a nice day.

If you need Google AdMob Alternatives you can check out Start Ad Platfrom.

Источник

Creating Custom Radio Groups & Radio Buttons in Android

Radio Group and Radio Button are two great components provided by the Android Framework, but unfortunately they often cannot satisfy all requirements. In this case there are several possible ways to get missing functionality, for example, use third-party libraries or create your own custom view components. In this tutorial I am going to explain the latter option. It is always a great idea to learn internals and understand what is going on under the hood.

Introduction

This tutorial is intended to explain how to create custom Radio Group and Radio Button components. There are lot of related topics addressed in this guide like Custom Views, Compound Views, View Groups. However, I won’t cover this topics in great details as far as there are lot of great tutorials out there. This tutorial supposes some basic knowledge of the Android Framework and the Java language. Furthermore you can find the link to the source code at the end of the article.

Step 1 — Creating a Custom Radio Button

First of all we need to find a design prototype to implement it in our custom Radio Button.

Design inspiration

I have found this great design prototype of the settings screen. Here you can see three radio buttons that are used as presets. This is a great choice from the UX perspective that lets a user easily choose from standard, in this case time, presets.

We are going to create a similar custom radio button, but in addition there will be an Edit Text view in order to enter custom values, however this is not related to the main purpose of the guide.

Creating a compound view

A compound view is a group of views or even view groups created for reusability and consistency. Furthermore such views could be enhanced programmatically as well.

Let’s start by creating the hierarchy of our compound radio button.

As you can see it is quite simple and contains only two Text View components.

Custom Radio Button XML File

To get started, create the /res/layout/custom_preset_button.xml XML file that will be used as the layout file for the compound view.

Please make sure you are using the tag. This tag helps to eliminate redundant view groups when a file with the tag is included into another layout or used as the layout file for a compound view.

Implementing a custom Radio Button

Next, we need to create a compound view class that will inflate the created layout file. Let’s call it PresetValueButton. We will extend the Relative Layout view group, because it is the most appropriate view group for this purpose. Here is the final implementation, let’s discuss the most interesting parts.

Читайте также:  Как обрезать мелодию для звонка андроид

We have defined the following custom attributes:

  • presetButtonValueText – Value text
  • presetButtonUnitText – Unit text
  • presetButtonValueTextColor – Value text color
  • presetButtonUnitTextColor – Unit text color
  • presetButtonPressedTextColor – Text color for both labels for the pressed state

The RadioCheckable interface

In order to define common properties and methods that a radio button must have to be a part of a radio group create the following RadioCheckable interface.

As you can see from the code above, our interface extends the Checkable interface defined in the Android Framework.

You may wonder what is the purpose of these two methods addOnCheckChangeListener and removeOnCheckChangeListener . Let’s see the implementation in the PresetValueButton class.

I’ve decided to use multiple listeners (add instead of set method), since the default implementation of the RadioButton class contains two listeners, one is available to a user and the second one is used just by the parent RadiouGroup class. Have a look at this snippet from the CompoundButton class.

Handling click and touch events

As you may have already noticed click and touch events are handled in the specific way.

This decision is the result of the peculiarity of handling click events and appearance of a button. When a user clicks on a radio button the text color should be set to presetButtonPressedTextColor and then reset to the normal state on the up action. Therefore this is handled manually, in addition if user has set its own touch handler it will be called after the switch statement.

Step 2 — Creating a Custom Radio Group

Now it is time to create a custom radio group. A lot of ideas and implementation details are taken from the default RadioGroup class. Our custom radio group class extends the LinearLayout view group as it is the most suitable container for this purpose.

Listeners

There are three listeners defined in the class:

  • OnCheckedChangeListener: Listener that is set by a user in order to listen for check change events.
  • PassThroughHierarchyChangeListener: This listener is used the internal purpose only. The radio group is notified when a child view is added or removed.
  • RadioCheckable.OnCheckedChangeListener: This listener is assigned to a child radio button when it is added.

Let’s look closer at the PassThroughHierarchyChangeListener implementation.

As it has been just mentioned, on line 12 mChildOnCheckedChangeListener is added to a child view, hence the radio group will be notified about child views click/change events. On line 14 we are adding a child view to the hash map in order to cache child views, as a result we do not need to call the findViewById method whenever we need a child view.

It is worthwhile to mention that we defined the custom attribute for presetting id in the XML file, similarly to the default RadioGroup implementation. Therefore you can set a view id in the XML layout file to make this view checked by default.

Step 3 — Using custom components

Layout file example

Finally, let’s test our custom components. Create the following XML layout file.

Источник

Оцените статью