Programming

CheckBox의 색상을 변경하는 방법은 무엇입니까?

procodes 2020. 5. 11. 21:20
반응형

CheckBox의 색상을 변경하는 방법은 무엇입니까?


CheckBoxAndroid 에서 기본 색상을 어떻게 변경 합니까?
기본적으로 CheckBox색상은 녹색이며이 색상을 변경하고 싶습니다.
그것이 가능하지 않다면 어떻게 커스텀을 만드는지 알려주십시오 CheckBox.


당신이 경우 minSdkVersion21+ 사용 인 android:buttonTint체크 박스의 색상을 업데이트하는 속성 :

<CheckBox
  ...
  android:buttonTint="@color/tint_color" />

AppCompat 라이브러리를 사용하고 21 미만의 Android 버전을 지원하는 프로젝트에서는 compat 버전의 buttonTint속성을 사용할 수 있습니다 .

<CheckBox
  ...
  app:buttonTint="@color/tint_color" />

이 경우 서브 클래스를 만들고 싶다면 대신 CheckBox사용 AppCompatCheckBox하는 것을 잊지 마십시오 .

이전 답변 :

속성을 CheckBox사용하여 드로어 블을 변경할 수 있습니다 android:button="@drawable/your_check_drawable".


XML에서 직접 색상을 변경할 수 있습니다. buttonTint상자에 사용 : (API 레벨 23 기준)

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:buttonTint="@color/CHECK_COLOR" />

appCompatCheckbox v7이전 API 레벨 에서이 작업을 수행 할 수도 있습니다.

<android.support.v7.widget.AppCompatCheckBox 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    app:buttonTint="@color/COLOR_HERE" /> 

styles.xml에서 원하는 색상을 얻도록 확인란의 Android 테마를 설정할 수 있습니다.

<style name="checkBoxStyle" parent="Base.Theme.AppCompat">
    <item name="colorAccent">CHECKEDHIGHLIGHTCOLOR</item>
    <item name="android:textColorSecondary">UNCHECKEDCOLOR</item>
</style>

그런 다음 레이아웃 파일에서 :

<CheckBox
     android:theme="@style/checkBoxStyle"
     android:id="@+id/chooseItemCheckBox"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>

android:buttonTint="@color/CHECK_COLOR"이 방법을 사용 하는 것과 달리 Api 23에서 작동합니다.


프로그래밍 버전 :

int states[][] = {{android.R.attr.state_checked}, {}};
int colors[] = {color_for_state_checked, color_for_state_normal}
CompoundButtonCompat.setButtonTintList(checkbox, new ColorStateList(states, colors));

buttonTint21 개 이상의 API 버전에서 버튼 색상 및 색상 선택기를 변경하는 데 사용 합니다.

<android.support.v7.widget.AppCompatCheckBox
                android:id="@+id/check"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:buttonTint="@color/checkbox_filter_tint"
                tools:targetApi="21"/>

res / colors / checkbox_filter_tint.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/light_gray_checkbox"
          android:state_checked="false"/>
    <item android:color="@color/common_red"
          android:state_checked="true"/>
</selector>

내장 안드로이드 뷰를 구성하고 프로젝트에 새로운 스타일을 추가하는 방법으로 안드로이드에서 스타일 접근 방식을 사용하는 것이 좋습니다.

<style name="yourStyle" parent="Base.Theme.AppCompat">
    <item name="colorAccent">your_color</item> <!-- for uncheck state -->
    <item name="android:textColorSecondary">your color</item> <!-- for check state -->
</style>

android : theme = "@ style / youStyle"확인란의 테마에이 스타일을 추가합니다.

도움이 되었기를 바랍니다.


XML에 buttonTint 추가

<CheckBox
      android:id="@+id/chk_remember_signup"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:buttonTint="@android:color/white"
      android:text="@string/hint_chk_remember_me" />

styles.xml파일에 다음 줄을 추가 하십시오.

<style>
    <item name="android:colorAccent">@android:color/holo_green_dark</item>
</style>

buttonTint는 나를 위해 노력했다.

android : buttonTint = "@ color / white"

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:id="@+id/agreeCheckBox"
    android:text="@string/i_agree_to_terms_s"
    android:buttonTint="@color/white"
    android:layout_below="@+id/avoid_spam_text"/>

나는 같은 문제에 직면했고, 아래 기술을 사용하여 해결책을 얻었습니다. 복사 btn_check.xml에서 android-sdk/platforms/android-#(version)/data/res/drawable프로젝트의 당김 폴더 및 사용자 정의 이미지에 이미지 상태 '오프'를 '사용'을 변경합니다.
그런 다음 XML이 필요합니다.android:button="@drawable/btn_check"

<CheckBox
    android:button="@drawable/btn_check"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true" />

다른 기본 Android 아이콘을 사용하려는 경우 다음을 사용할 수 있습니다.

android:button="@android:drawable/..."

checkbox줄의 코드를 사용하여 색상을 변경할 수 있습니다

android:buttonTint="@color/app_color" //whatever color


drawable에서 자신의 XML을 만들고 android : background = "@ drawable / your_xml"로 사용할 수 있습니다.

테두리 모서리에 모든 것을 줄 수 있다는 점에서

<item>
    <shape>
        <gradient

            android:endColor="#fff"
            android:startColor="#fff"/>
        <corners
            android:radius="2dp"/>
        <stroke
            android:width="15dp"
            android:color="#0013669e"/>

    </shape>
</item>


Hi 이것은 어두운 테마와 밝은 테마의 테마 코드입니다.

<attr name="buttonsearch_picture" format="reference"/>
<attr name="buttonrefresh_picture" format="reference"/>

<style name="Theme.Light" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@color/white</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:textColorPrimary">@color/black</item>
    <item name="android:textColorSecondary">@color/black</item>
    <item name="android:textColor">@color/material_gray_800</item>
    <item name="actionOverflowButtonStyle">@style/LightOverflowButtonStyle</item>
    <item name="buttonsearch_picture">@drawable/ic_search_black</item>
    <item name="buttonrefresh_picture">@drawable/ic_refresh_black</item>
</style>

<style name="Theme.Dark" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@color/white</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:textColorPrimary">@color/white</item>
    <item name="android:textColorSecondary">@color/material_gray_500</item>
    <item name="android:textColor">@color/material_gray_800</item>
    <item name="actionOverflowButtonStyle">@style/DarkOverflowButtonStyle</item>
    <item name="buttonsearch_picture">@drawable/ic_search_white</item>
    <item name="buttonrefresh_picture">@drawable/ic_refresh_white</item>
    <item name="android:colorBackground">#ffffff</item>
    <item name="android:alertDialogTheme">@style/LightDialogTheme</item>
    <item name="android:alertDialogStyle">@style/LightDialogTheme</item>
  <!-- <item name="android:textViewStyle">@style/AppTheme.Widget.TextView</item>-->
    <item name="android:popupMenuStyle">@style/PopupMenu</item>
</style>

체크 박스 색상을 변경하려면 "colorAccent"속성이 체크 상태에 사용되고 "android : textColorSecondary"상태 체크에 사용됩니다.

"actionOverflowButtonStyle" will use for change the color of overflow icon in the Action bar.

"buttonsearch_picture" attribute will use for change tint color of Action Button in Action Bar.This is custom Attribute in style.xml

<attr name="buttonsearch_picture" format="reference"/>

Same is for refresh button which i am using in my app.

"android:popupMenuStyle" attribute is using to get Light theme popup menu style in Dark theme.

<style name="PopupMenu" parent="Theme.AppCompat.Light.NoActionBar">
</style>

And this is toolbar Code which I am using in my Rocks Player App.

 <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    app:contentInsetStart="0dp"
    android:title="Rocks Player"
    android:layout_width="match_parent"
    android:elevation="4dp"
    android:layout_height="48dp"
    app:layout_scrollFlags="scroll|enterAlways"
    android:minHeight="48dp"
    app:titleTextAppearance="@style/Toolbar.TitleText"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:background="?attr/colorPrimary"
    >
</android.support.v7.widget.Toolbar>

Themes:-

 <style name="AppTheme0" parent="Theme.Light">
    <item name="colorPrimary">#ffffff</item>
    <item name="colorPrimaryDark">#cccccc</item>
    <item name="colorAccent">#0294ff</item>
</style>

<style name="AppTheme1" parent="Theme.Dark">
    <item name="colorPrimary">#4161b2</item>
    <item name="colorPrimaryDark">#4161b2</item>
    <item name="colorAccent">#4161b2</item>
</style>

create an xml Drawable resource file under res->drawable and name it, for example, checkbox_custom_01.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/checkbox_custom_01_checked_white_green_32" />
  <item 
   android:state_checked="false" 
   android:drawable="@drawable/checkbox_custom_01_unchecked_gray_32" />
</selector>

Upload your custom checkbox image files (i recommend png) to your res->drawable folder.

Then go in your layout file and change your checkbox to

<CheckBox
    android:id="@+id/checkBox1"
    android:button="@drawable/checkbox_custom_01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:text="CheckBox"
    android:textSize="32dip"/>

you may customize anything, as long as android:button points to the correct XML file you created before.

NOTE TO NEWBIES: though it is not mandatory, it is nevertheless good practice to name your checkbox with a unique id throughout your whole layout tree.


You can change the background color of the <CheckBox> by embedding it inside a <LinearLayout>. Then change the background color of <LinearLayout> to the color you want.


You should try below code. It is working for me.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/checked" 
          android:state_checked="true">
        <color android:color="@color/yello" />
    </item>
    <!-- checked -->
    <item android:drawable="@drawable/unchecked" 
          android:state_checked="false">
        <color android:color="@color/black"></color>
    </item>
    <!-- unchecked -->
    <item android:drawable="@drawable/checked" 
          android:state_focused="true">
        <color android:color="@color/yello"></color>
    </item>
    <!-- on focus -->
    <item android:drawable="@drawable/unchecked">
        <color android:color="@color/black"></color>
    </item>
    <!-- default -->
</selector>

and CheckBox

<CheckBox
    Button="@style/currentcy_check_box_style"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="20dp"
    android:text="@string/step_one_currency_aud" />

If you are going to use the android icons, as described above ..

android:button="@android:drawable/..."

.. it's a nice option, but for this to work - I found you need to add toggle logic to show/hide the check mark, like this:

    checkBoxShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        // checkbox status is changed from uncheck to checked.
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            int btnDrawable = android.R.drawable.checkbox_off_background;

            if (isChecked)
            {
                btnDrawable = android.R.drawable.checkbox_on_background;
            }

            checkBoxShowPwd.setButtonDrawable(btnDrawable);

        }
    });

You can use the following two properties in "colors.xml"

<color name="colorControlNormal">#eeeeee</color>
<color name="colorControlActivated">#eeeeee</color>

colorControlNormal is for the normal view of checkbox, and colorControlActivated is for when the checkbox is checked.


100% robust approach.

In my case, I didn't have access to the XML layout source file, since I get Checkbox from a 3-rd party MaterialDialog lib. So I have to solve this programmatically.

  1. Create a ColorStateList in xml:

res/color/checkbox_tinit_dark_theme.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/white"
        android:state_checked="false"/>
    <item android:color="@color/positiveButtonBg"
        android:state_checked="true"/>
</selector>
  1. Then apply it to the checkbox:

    ColorStateList darkStateList = ContextCompat.getColorStateList(getContext(), R.color.checkbox_tint_dark_theme);
    CompoundButtonCompat.setButtonTintList(checkbox, darkStateList);
    

P.S. In addition if someone is interested, here is how you can get your checkbox from MaterialDialog dialog (if you set it with .checkBoxPromptRes(...)):

CheckBox checkbox = (CheckBox) dialog.getView().findViewById(R.id.md_promptCheckbox);

Hope this helps.


Use this to change the background of the Checkbox in dynamically in your java code

//Setting up background color on checkbox. checkbox.setBackgroundColor(Color.parseColor("#00e2a5"));

This answer was from a this site. You can also use this site to convert your RGB color to the Hex value you need to feed the parseColor

참고URL : https://stackoverflow.com/questions/5854047/how-to-change-the-color-of-a-checkbox

반응형