Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically styling Android's CheckBox

I got a class which extends Activity and programmatically adding some View items.

CheckBox checkBox = new CheckBox(this, null, android.R.style.Widget_CompoundButton_Star);

I'd like to set some checkBoxes styled as the Android SDK stars. I can't see any check box after I set its style to that Widget_CompoundButton_Star. Although that SDK style apparently works when directly placing in a xml.

Am I missing something here? THX

// As Pragnani said. Using android.R.attr.starStyle instead works.

like image 534
Yuri Avatar asked Feb 19 '13 17:02

Yuri


People also ask

How to set CheckBox checked in Android programmatically?

By default, the android CheckBox will be in the OFF (Unchecked) state. We can change the default state of CheckBox by using android:checked attribute. In case, if we want to change the state of CheckBox to ON (Checked), then we need to set android:checked = “true” in our XML layout file.

How can I change the color of my CheckBox in Android?

If you want to change checkbox color then "colorAccent" attribute will use for checked state and "android:textColorSecondary" will use for unchecking state. "actionOverflowButtonStyle" will use for change the color of overflow icon in the Action bar. Same is for refresh button which i am using in my app.

How to add CheckBox in XML?

To define the click event handler for a checkbox, add the android:onClick attribute to the <CheckBox> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.


2 Answers

You can set style to view programmatically with ContextThemeWrapper.

CheckBox mCheckBox = new CheckBox(new ContextThemeWrapper(context, R.style.MyCheckBox));
like image 76
Roman Smoliar Avatar answered Sep 26 '22 13:09

Roman Smoliar


I've arrived here looking for styling the text of the CheckBox instead of the Drawable, and I find the solution by another way. But hey! Let me share the solution to the myself of the future.

Instead of:

CheckBox cb = new CheckBox(this, null, R.style.yourstyle);

Use:

CheckBox cb = new CheckBox(this);
cb.setTextAppearance(this, R.style.yourstyle);

Hope it helps to solve the topic of the question!

like image 41
Roc Boronat Avatar answered Sep 23 '22 13:09

Roc Boronat