Android: установите цвет CheckBox
Я обыскал несколько мест и, похоже, не смог определить CheckBox
для рамки рамки. Может ли кто-нибудь указать мне правильное направление?
Вот как он выглядит непроверенным (может едва видеть окно)
![enter image description here]()
Вот проверенное состояние
![enter image description here]()
Вот что я пытаюсь сделать так:
![enter image description here]()
Ответы
Ответ 1
Для этого вы можете использовать для этого XML файл. Сохраните приведенный ниже xml-код в папке drawables
, назовите его custom_checkbox.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:drawable="@drawable/cbchk_blue"
android:state_focused="false">
</item>
<item android:state_checked="true"
android:drawable="@drawable/cbchk_blue"
android:state_focused="true">
</item>
<item android:state_checked="false"
android:drawable="@drawable/cbunchk_blue"
android:state_focused="false">
</item>
<item android:state_checked="false"
android:drawable="@drawable/cbunchk_blue"
android:state_focused="true">
</item>
</selector>
Затем используйте этот файл в качестве фона вашего флажка, например:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/custom_checkbox"
android:id="@+id/checkBox" />
Здесь я загружаю свои собственные изображения, которые я использовал вместо cbchk_blue и cbunchk_blue
![Unchecked CheckBox]()
![Checked CheckBox]()
Ответ 2
Такая же проблема возникает и при использовании темы Holo Dark for Activity и на белом фоне. Таким образом, флажок имеет стиль Dark. Простое обходное решение - прямое задание фона от Android Holo Light:
int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
checkBox.setButtonDrawable(id);
Вы можете найти отличный обзор, как все это работает в следующем ответе:
fooobar.com/questions/127186/...
Ответ 3
Начиная с Android 5 и API уровня 21 можно свободно выбирать цвета флажков (и многих других виджетов). Добавьте в свой values-v21/styles.xml
следующий код (при условии, что у вас есть резерв для более ранних API-интерфейсов в values/styles.xml
:
<style name="CustomCheckBox">
<item name="android:theme">@style/CheckBoxAppTheme</item>
</style>
<style name="CheckBoxAppTheme">
<item name="android:colorAccent">
@color/theFillColorInCheckedState
</item>
<item name="android:colorControlNormal">
@color/theBorderColorInUncheckedState
</item>
<item name="android:colorControlHighlight">
@color/theBackgroundColorWhenFocusingTheCheckBox
</item>
</style>
Затем вам просто нужно применить стиль к своему флажку в своем макете:
<CheckBox
style="@style/CustomCheckBox" />
Что это, флажки появляются в ваших любимых цветах!
Ответ 4
Хорошо, так что извините, но большинство из этих ответов неполны или имеют небольшую ошибку. Элементы управления Styling в разных версиях Android - это эпическая боль в заднице. Вытащив мои волосы в течение нескольких дней на проект с очень жесткими ограничениями конструкции, я, наконец, сломался и написал тестовое приложение, а затем действительно выкопал и протестировал различные решения там для стилейных переключателей и флажков, поскольку, когда у дизайна есть один он часто имеет другой. Вот что я нашел...
Во-первых: Вы не можете начертить ни один из них, но вы можете применить тему для всех из них или только один из них.
Второе:. Вы можете сделать все это из XML, и вам не нужны другие значения-v21/styles.xml.
В-третьих:, когда дело доходит до коммутаторов, у вас есть два основных варианта, если вы хотите поддерживать более старые версии Android (например, я уверен, что вы это делаете)...
- Вы можете использовать
SwitchCompat
, и вы сможете сделать его похожим на разных платформах.
- Вы можете использовать
Switch
, и вы сможете обсуждать его с остальной частью темы, или только с этим конкретным коммутатором, и на более старых версиях Android вы просто увидите нерасширенный старый квадратный переключатель.
Хорошо теперь для простого ссылочного кода. Опять же, если вы создадите простой Hello World! и отбросьте этот код, вы можете играть в своем сердце. Все это плита котла здесь, поэтому я просто собираюсь включить XML для активности и стиля...
activity_main.xml...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="'Styled' SwitchCompat" />
<android.support.v7.widget.SwitchCompat
android:id="@+id/switch_item"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false"
android:textOff="OFF"
android:textOn="ON"
app:switchTextAppearance="@style/BrandedSwitch.text"
app:theme="@style/BrandedSwitch.control"
app:showText="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Themed SwitchCompat" />
<android.support.v7.widget.SwitchCompat
android:id="@+id/switch_item2"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Themed Switch" />
<Switch
android:id="@+id/switch_item3"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false"
android:textOff="OFF"
android:textOn="ON"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="'Styled' Switch" />
<Switch
android:id="@+id/switch_item4"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false"
android:textOff="OFF"
android:textOn="ON"
android:theme="@style/BrandedSwitch"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="'Styled' CheckBox" />
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false"
android:theme="@style/BrandedCheckBox"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Themed CheckBox" />
<CheckBox
android:id="@+id/checkbox2"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false"/>
</RelativeLayout>
styles.xml...
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#3F51B5</item>
<item name="colorPrimaryDark">#303F9F</item>
<item name="colorAccent">#FF4081</item>
</style>
<style name="BrandedSwitch.control" parent="Theme.AppCompat.Light">
<!-- active thumb & track color (30% transparency) -->
<item name="colorControlActivated">#e6e600</item>
<item name="colorSwitchThumbNormal">#cc0000</item>
</style>
<style name="BrandedSwitch.text" parent="Theme.AppCompat.Light">
<item name="android:textColor">#ffa000</item>
<item name="android:textSize">9dp</item>
</style>
<style name="BrandedCheckBox" parent="AppTheme">
<item name="colorAccent">#aaf000</item>
<item name="colorControlNormal">#ff0000</item>
</style>
<style name="BrandedSwitch" parent="AppTheme">
<item name="colorAccent">#39ac39</item>
</style>
Я знаю, я знаю, вы слишком ленивы, чтобы построить это, вы просто хотите, чтобы ваш код был написан. Я понял. Вот как это выглядит, когда вы запускаете его...
API_21:
![API 21]()
API_18:
![API18]()
Ответ 5
Он задается чертежами: android.R.drawable.checkbox_off_background
и android.R.drawable.checkbox_on_background
Ответ 6
Вы можете установить цвет CHECKBOX как API21 и выше
Android: buttonTint = "@цвет/YOUR_COLOR"
<CheckBox
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:buttonTint="@color/YOUR_COLOR" />
Для поддержки старой версии используйте AppCompatCheckBox библиотеки V7
Приложение: buttonTint = "@цвет/YOUR_COLOR"
<android.support.v7.widget.AppCompatCheckBox
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:buttonTint="@color/YOUR_COLOR" />
Ответ 7
Это будет самый эффективный способ.
Android: buttonTint = "@цвет/черный"