1

I'm trying to set the background colour of a check box when it has been checked then and if it is unchecked then to remove that colour.

Can anybody help me find the Id of the checkbox then to check if it is checked. I have set in my XML sheet android:onClick="handleCheckBoxClick"

For you to get an idea of how it looks I have roughly 25 check boxes. which I need the same doing to them when they are pressed.

Is it possible to have one block of code or would it need to be repeated for each checkbox?

EDIT: Forgot to mention this is within a fragment (if that makes any difference)

public void handleCheckBoxClick(View view) { int chkID = view.getId(); if (){ }else{ } //find which checkbox was checked then get its id /* * if checked then * change background colour to blue * if unchecked then * remove background colour * */ } 

The colour part i'll try myself as do need to learn .

4
  • use drawable for setting background. Commented Oct 18, 2013 at 10:39
  • you can set background color or you may set image from drawable Commented Oct 18, 2013 at 10:45
  • use an xml with selector. Refer this Commented Oct 18, 2013 at 10:53
  • thanks for quick replys everyone, but just to clarify its not the button part i would like change but the background of where the text is Commented Oct 18, 2013 at 11:04

3 Answers 3

2

The preferable way is to use a custom checkbox. To set background in both checked state and unchecked state by simply using drawable XML file.

Here is an another simple example to do it. The following picture is taken from this page:

]

Sign up to request clarification or add additional context in comments.

1 Comment

First link is broken and pointing to something pretty sketchy looking.
0

if you are interested in changing the background color of the checkbox(button) use

mycheckbox.setButtonDrawable(R.drawable.otherbackground); 

where someother background is an image in the drawable folder to which background you want your checkbox to be changed

try following

mycheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mycheckbox.setButtonDrawable(R.drawable.imageWhenActive); } else { mcheckbox.setButtonDrawable(R.drawable.imageWheninactive); } } }); 

Comments

0

Here is Your Answer

public void handleCheckBoxClick(View view) { CheckBox chkBox = (CheckBox) findViewById(view.getId()); if(chkBox.isChecked()) { chkBox.setBackgroundColor(color.blue); //or chkBox.setButtonDrawable(R.drawable.imagechk); } else { chkBox.setBackgroundColor(color.red); //or chkBox.setButtonDrawable(R.drawable.imageunchk); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.