Fustigador
Fustigador

Reputation: 6459

How to set programatically a selector to a checkbox

I need to set a selector to checkboxes that are created programatically, this way:

var cbAll = new CheckBox(Activity);
            LinearLayout.LayoutParams llAll = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);

            cbAll.Text = "All zones";
            llAll.LeftMargin = 27;
            llAll.TopMargin = 24;
            cbAll.ButtonDrawable = //what to put here?

My selector (named cb_edit.xml) in drawable folder:

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

Upvotes: 1

Views: 65

Answers (2)

FreakyAli
FreakyAli

Reputation: 16479

  • First, add an XML into your drawable folder:

CheckBoxDrawable.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/CheckedImage" />
  <item android:state_checked="false" android:drawable="@drawable/UnCheckedImage" />
</selector>
  • Then declare the checkbox and set the button drawable to it something like this:

    Checkbox btnOption = new Checkbox(context);
    btnOption.SetButtonDrawable(Resource.Drawable.CheckBoxDrawable);
    

That should make it work in case it does not revert

Upvotes: 0

Ashwini Bhat
Ashwini Bhat

Reputation: 500

i don't know what exactly you trying.but if u setting background then try this

cbAll.SetBackgroundResource( Resource.Drawable.cb_edit); 

Upvotes: 1

Related Questions