Reputation: 53
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 .
Upvotes: 1
Views: 9101
Reputation: 15408
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:
Upvotes: 2
Reputation: 5707
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);
}
}
Upvotes: 0
Reputation: 30648
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);
}
}
});
Upvotes: 0