Is it possible to change the box color of a CheckBox via a program (runtime)?
I would like to change the white color of the box highlighted in the image.
This color is defined by the theme you use, so a first output would be to change the theme in runtime - odd but possible.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
// chame setTheme antes de criar qualquer View
setTheme(android.R.style.Theme_Dark);
// ...
setContentView(R.layout.main);
}
If you want to change the theme after the creation of Activity
, you will have to recreate the activity and inform the new theme to be used.
If it seems very inefficient, you can also change the buttonTintList
of CheckBox
. To do this, just call CheckBox#setButtonTintList(ColorStateList)
and you change how the CheckBox will be drawn in each state. There are two ways to create a ColorStateList
:
Code
private static final int[][] CHECK_BOX_STATES = new int[][] {
new int[] {-android.R.attr.state_enabled}, // desabilitado
new int[] { android.R.attr.state_checked}, // marcado
new int[] {-android.R.attr.state_checked}, // desmarcado
new int[] {} // default
};
private static final int[] CHECK_BOX_COLORS = new int[] {
Color.GRAY,
Color.CYAN,
Color.MAGENTA,
Color.MAGENTA
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
CheckBox checkBox = (CheckBox) findViewById(R.id.cb_id);
// limpa buttonTintList
checkBox.setButtonTintList(null);
checkBox.setButtonTintList(new ColorStateList(CHECK_BOX_STATES, CHECK_BOX_COLORS));
// ...
}
XML
assets / checkbox_style.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#ffff00" />
<item android:state_checked="true"
android:color="#00ffff" />
<item android:state_checked="false"
android:color="#ff00ff" />
</selector>
Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
CheckBox checkBox = (CheckBox) findViewById(R.id.cb_id);
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(getAssets().open("checkbox_style.xml"), "UTF-8");
checkBox.setButtonTintList(ColorStateList.createFromXml(getResources(), parser));
} catch (XmlPullParserException | IOException e) {
e.printStackTrace();
}
// ...
}
In neither case did I ever change the color of the CheckBox. Via code the color changes only once for each state (for example: it changes when it marks, but when it does not return it does not return the state color unchecked), already via XML the emulator throws a bizarre exception complaining that the item
tag needs to have a attribute android:color
.
For more information look at the documentation: CheckBox , CompoundButton # setButtonTintList (ColorStateList) , ColorStateList .
I hope I have helped.