- 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
- How to create CheckBoxes in Android
- Creating a CheckBox
- Step 1: Set up the android development environment
- Step 2: Create An Android Project
- Step 3: Create the required layouts
- Step 4: Create the required activities
- Step 5: Declaring the Activities in AndroidManifest.xml
- Step 6: Run your application
- Creating custom CheckBox
- About Krishna Srinivasan
- Leave a Reply Cancel reply
- Follow Us
- Android Tutorials for Beginners
- 10 Tips to Increase Windows 10 Performnace
- Friday, May 31, 2013
- Custom CheckBox in Android
- Android Development Tutorial
- custom_checkbox_design.xml
- main.xml
- Custom checkboxes in android
- About
- Resources
- License
- Releases
- Packages 0
- Contributors 2
- Languages
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
Если запустить пример на старом устройстве, то никакой анимации не увидим, но код будет работать без ошибок. На новых устройствах анимация будет работать.
Источник
How to create CheckBoxes in Android
CheckBox is a fully implemented widget provided by Android. Checkboxes are used for selecting one or more options from a set. In this tutorial we would be discussing about creating the standard and customized CheckBoxes. CheckBox is a special type of button that has two states, checked and unchecked.
The CheckBox in Android is as below.
As you can see the above picture, CheckBox in android has a TextView whose properties can be used to format the widget. One must avoid using a single checkbox to turn an option off or on. The checked event of the CheckBox is handled by setting the onCheckedChangeListener for the CheckBox. The callback for the listener is onCheckedChanged(), which is responsible for receiving the CheckBox whose state has changed and its new state.
Creating a CheckBox
You can create a CheckBox by creating an instance of android.widget. CheckBox as below,
Within Java, you can manage the state of a checkbox by using the following,
- isChecked() : used to obtain the state of the CheckBox.
- toggle() : toggles the CheckBox state.
- setChecked() : Used to set the CheckBox state to checked or unchecked.
Let us now create a sample application that shows the usage of CheckBoxes in Android.
Step 1: Set up the android development environment
This topic has already been discussed in one of our previous posts Environment. Please refer the post for more queries. I would be using Android 4.0 for this example
Step 2: Create An Android Project
Create an Android project named “CheckBoxDemo” with the launcher activity CheckBoxDemoActivity.java. For more information on how to create a new project in android, please refer to the post Create an android project.
Step 3: Create the required layouts
I would be using main.xml layout file. To know more about layout xml files, please go through the post Layouts. Open the main.xml file and paste the below code.
As you can see in the above code, the main.xml has a RelativeLayout which in turn has a textview and a checkbox. The CheckBox tag is used to create the Checkbox widget.
Step 4: Create the required activities
The launcher Activity CheckBoxDemoActivity.java. has the below code,
Each CheckBox is managed separately. As you can see, we have registered a listener which is to be notified when the state of the Chekcbox changes. In this example, we would be changing the text of the checkbox when the user clicks on it.
As you can notice, we have registered onCheckedChangeListener and not onClickedListener as in the case of normal button. The callback for the listener is onCheckedChanged(). This callback receives the CheckBox whose state has changed.
Step 5: Declaring the Activities in AndroidManifest.xml
The AndroidManifest.xml file has the below code. To know more about manifest file, please refer the post Manifest.
Step 6: Run your application
Select your project->Right click->Run As->Android Application
Your launcher activity opens up as below,
At first the CheckBox is in unchecked state as shown by the TextView. Clicking the CheckBox immediately updates its text as below,
You can see the changed text in the above figure. Unchecked has been changed to checked when the CheckBox state is checked.
Creating custom CheckBox
Till now we have studied how to create a standard CheckBox in Android. So now you would be learning how to create custom CheckBox in android. Like all widgets, the standard CheckBox can be customized. You can change the color, shape and behaviors. This is done by creating a XML selector and assigning that selector to the CheckBox in your layout. selectors are the elements provided by android which allows users to create a single reference to multiple images and the conditions under which they shuold be visible. Follow below steps for creating custom CheckBoxes.
- Prepare two images for CheckBox state. Here in this tutorial I would be using a Red square for CheckBox unchecked state and Green square for a checked state. Place these images in res/drawable folder. checked.png is to display when the CheckBox is in checked state. unchecked.png is to display when the CheckBox is in unchecked state.
- Create a selector XML in res/drawable folder. The content of the selector XML checkbox_selector.xml is as below,
The project structure with selector XML is as below,
- Assign the selector to your CheckBox in your layout – Unlike buttons, Checkboxes have a slightly different mechanism for changing the states. In case of CheckBox, the background is not associated with the state so assigning the selector to the checkbox is done through another attribute called android:button. The below is the code of the main.xml for creating custom checkbox.
Now Run your code with the changes made to the project, The custom adapter is displayed as below,
Change the state of the checked, you can see the changed color of the checkbox drawable,
This is how you can create and use the standard and custom Checkbox in android. CheckBox can be added to AlerDialogs. To know more about how to add CheckBoxes to AlertDialogs, please refer the post AlertDialogCheckBox Hope this turorial served your purpose. Feel free to post your comments.
About Krishna Srinivasan
He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Follow Us
As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.
Источник
Android Tutorials for Beginners
Learn Android very Easily and Step by Step with this blog.
10 Tips to Increase Windows 10 Performnace
Friday, May 31, 2013
Custom CheckBox in Android
Android Development 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»/>
Источник
Custom checkboxes in android
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.
Источник