Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Created Radio Button or CheckBox does not use Color Accent

Using v21 AppCompat we can set custom color themes like following:

<style name="Theme.MyTheme" parent="Theme.AppCompat">
    <!-- customize the color palette -->
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
</style>

But I have a bunch of dynamically created checkboxes and radio buttons which are not inflated from xml. These dynamically created objects do not inherit the color accent that I have specified. What can I do to set these color accents properly?

like image 218
Neoh Avatar asked Nov 03 '14 16:11

Neoh


3 Answers

You can't do anything about it other than creating a layout file with just one CheckBox in it and than inflate it.

As the developers site stated: The material theme design can only be applied when loading views using a layout inflater.

This is because the new material design backport hooks into the layout inflation process.

Source: http://android-developers.blogspot.nl/2014/10/appcompat-v21-material-design-for-pre.html

Edit:
In newer versions 22.1+ of AppCompat v7 widgets like CheckBox and RadioButton can be created dynamically (no longer hidden/internal API).

Currently these widgets are supported:

  • AppCompatAutoCompleteTextView
  • AppCompatButton
  • AppCompatCheckBox
  • AppCompatCheckedTextView
  • AppCompatEditText
  • AppCompatMultiAutoCompleteTextView
  • AppCompatRadioButton
  • AppCompatRatingBar
  • AppCompatSpinner
  • AppCompatTextView
  • AppCompatSeekBar (since 23.1)
  • AppCompatImageButton (since 23.1)
  • AppCompatImageView (since 23.1)
like image 181
Rolf ツ Avatar answered Sep 26 '22 14:09

Rolf ツ


I ran into the same problem and now have a material_factory_* xml file for each of my dynamically created views. Its a bit annoying but it works:

// checkbox = new CeckBox(context);
checkbox = (CheckBox) View.inflate(context, R.layout.material_factory_checkbox, null);

And the material_factory_checkbox.xml file:

<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
like image 30
Simon Avatar answered Sep 24 '22 14:09

Simon


You can actually do something, apply a style on the inflating view like:

    <CheckBox
        android:id="@+id/check_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/save_password_label"
        android:theme="@style/CheckBoxStyle"
        />

with the style:

<style name="CheckBoxStyle" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorAccent">@color/colorPrimary</item>
</style>
like image 21
pierre Avatar answered Sep 25 '22 14:09

pierre