Android studio кастомный 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, то не составит никакого труда реализовать свои представления о дизайне.

Читайте также:  Iperf для android tv

В папке 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

Если запустить пример на старом устройстве, то никакой анимации не увидим, но код будет работать без ошибок. На новых устройствах анимация будет работать.

Источник

Android studio кастомный checkbox

Android UI Control Checkbox

September 08, 2017

To capture user selections out of given multiple options or to capture input for fields which have only two states, Checkbox is used. Android Checkbox is a subclass of CompoundButton which intern is a subclass of Button, so it inherits all the attributes from CompoundButton, Button, TextView and View.

Adding Checkbox to UI

You can add Checkbox to android UI by defining CheckBox element in xml manually or using android studio layout design tool which can be accessed by opening layout xml and clicking design tab. Below xml is an example of simple CheckBox definition.

Checkbox Attributes

To define checkbox, main attributes which need to be used are focusable, clickable, textAppearance, textColor, gravity, background, button, and buttonTint. These properties are usually set by device default styles which you can customize to change appearance of checkbox.

Chckbox Styles

Android platform provides styles including material styles for check box. If you set application theme to one of the app compact material themes, Widget.AppCompat.CompoundButton.CheckBox style is applied to checkbox.

Below screen shot shows checkboxes both in checked and unchecked states when application theme is set to Theme.AppCompat.

Customizing CheckBox Styles for Application

You can customize checkbox styles for entire application or specific check box. To change fill colors for all controls including checkbox, you need to set colorAccent to the desired color in your custom app-compact theme that will be applied to your application.

Below are custom app compact theme with colorAccent set to custom color and screen shot showing checkboxes in both states after applying the custom theme to application.

Читайте также:  Форматирование флешки для андроид юсб

Customizing Styles for Individual CheckBox

To customize individual checkboxes, first create custom theme by inheriting app compact checkbox theme and then apply it to individual checkbox using theme attribute.

Customizing checkbox color

To change checkbox color when it is in unchecked state, you need to set colorControlNormal attribute to the desired color. To change checkbox color when it is in checked state, attribute colorControlActivated needs to be set. You can make checkbox show different color when it is touched or highlighted using colorControlHighlight attribute.

If you want same color applied to checkbox in both states, you can use buttonTint attribute, but the style containing this property needs to be applied to checkbox as style.

Custom checkbox style.

Applying custom style to checkbox.

Checkbox custom style output.

Checkbox text color

To change text color of checkbox text, you can use textColorPrimaryDisableOnly or textColor attribute. If you define textColor style in your custom theme to change checkbox text color, it won’t work if style is applied as theme. You need to apply the custom style to check box using both style and theme in order for check box colors and checkbox text color to be effective. It is better to create two styles one containing check box colors that will be used as theme and second style containing text color for check box text that will be used as style, as shown in the below example. Or you can use textColorPrimaryDisableOnly attribute in custom style and apply it as theme to application or checkbox.

Customizing checkbox button shape

You can customize CheckBox shape by defining drawable as xml in res/drawable folder and setting button attribute of CheckBox to the drawable.

Below is an example of drawable xml definition for CheckBox. It uses cust_chk_select and cust_chk checkbox images for both states, which need to be saved in res/drawable folder.

Using custom drawable in checkbox style.

Custom CheckBox output.

If you need a kind of checkbox that uses colors instead of check mark to indicate whether a checkbox is selected or not, then you can define shapes as xml and use them as drawables as explained below.

Shape with one color saved in res/drawable as my_chk_checked.xml

Second shape with different color saved in res/drawable as my_chk_normal.xml

Selector drawable xml saved in res/drawable as my_chk.xml

Setting the button attribute of checkbox to the selector.

Checkbox Listener

Checkbox event can be handled by setting onClick attribute of Checkbox element in layout xml. To do that, first define a method as shown below and set it as a value for onClick attribute.

Checkbox click event can also be handled by adding on click listener to check box as shown below.

Setting Checkbox State

CheckBox state can be changed using checked attribute in layout xml. By default checkbox is unchecked. You can make it checked by setting checked attribute to true.

Читайте также:  Найти гаджеты для android

You can change the state of checkbox using setChecked method of Checkbox as shown below or you can use toggle method also.

Listview Checkbox

In your app if there are multiple options to be displayed for user selection, then presenting multiple options can be done using ListView and CheckBox. Below example shows how to display checkboxes with ListView by taking ecommerce category search filter as an example.

Activity layout

Activity layout contains ListView.

ListView item layout

ListView item layout is used to display each row of options and it contains TextView and CheckBox

Activity

ListView Custom Adapter

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

Android Tutorials for Beginners

Learn Android very Easily and Step by Step with this blog.

10 Tips to Increase Windows 10 Performnace

Tuesday, May 21, 2013

Customizing Checkboxes In Android

Learn Android Tutorial

In android we can customize the customize the default checkboxes. Default checkboxes are small and also not attractive, By using customized checkboxes we can design more attractive and better user interface.

To customize checkboxes we need to define our own drawables for checked and unchecked state.

In this example I have used these two drawables for checked and unchecked state.

We need to define the xml for our customized checkboxes

create the custom_checkbox_design.xml file and put it in drawable folder( if drawable folder is not there ,cerate it (inside res folder, and put custom_checkbox_design.xm file in this folder). It should look like following in pacakgae explorer

res
-> drawable
-> custom_checkbox_design.xml

custom_checkbox_design.xml

In checkbox set android:button property to the custom_checkbox_design.xml drawable like
android:button=» @drawable/custom_checkbox_design «

See the differences in default checkbox and customize checkbox in below screenshot.

main.xml

android:layout_width=»fill_parent»
android:layout_height=»fill_parent»
android:orientation=»vertical»
xmlns:android=»http://schemas.android.com/apk/res/android»>

android:id=»@+id/textView1″
android:layout_width=»fill_parent»
android:layout_height=»wrap_content»
android:layout_marginTop=»30dp»
android:gravity=»center_horizontal»
android:textSize=»25dp»
android:text=»Default Check box»/>

android:id=»@+id/textView1″
android:layout_width=»fill_parent»
android:layout_height=»wrap_content»
android:layout_marginTop=»30dp»
android:gravity=»center_horizontal»
android:textSize=»25dp»
android:text=»Customized Check box»/>

android:button=»@drawable/custom_checkbox_design»
android:textSize=»20dp»/>
android:button=»@drawable/custom_checkbox_design»
android:textSize=»20dp»/>

Источник

Android studio кастомный checkbox

Android Custom CheckBox

Android custom checkbox based on SmoothCheckBox

Attr Type Description
duration integer Animation Duration
stroke_width dimension The border width when unchecked
color_tick color Tick color (visible only when checked)
color_checked color Fill color when selected
color_unchecked color Fill color when unchecked
color_unchecked_stroke color Border color when unchecked

To publish on bintray, simply execute: ./gradlew clean assembleRelease bintrayUpload

About

Custom checkbox implementation for Android

Resources

License

Releases

Packages 0

Contributors 2

Languages

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

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