I want to create a custom Checkbox with four different states:
I did found here how to create a checkbox with custom images (with the states pressed, focused, hovered and default). But what I want instead is a way to cycle between the four states as follows:
PS: I know it's probably easier in an android app to just make a dropdown with the 4 states or a pop-up where you select one of the states. But I want among these two, this third option above, so users can decide for themselves which of the three settings they'll prefer.
PSS: While I'm typing this I came up with the idea of a button with the unchecked image, and when you click it it will replace the image-src to the next, while keeping everything else the same (like width/height and margin/padding). Is this the best approach for this situation, or does someone have a more elegant solution instead?
Thanks in advance for the responses.
As stated in the PSS, I only had the idea for the solution when I was typing the question above. I've used an ImageButton that changes it's source when it's clicked. Here is the code:
ImageButton in xml:
<ImageButton
android:id="@+id/ibtnCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/checkbox_content_description"
android:src="@drawable/checkbox_unchecked"
android:background="@drawable/transparent_button_background" />
transparent_button_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@android:color/transparent" />
<item android:state_pressed="true" android:drawable="@android:color/transparent" />
<item android:drawable="@android:color/transparent" />
</selector>
Activity:
public class MainActivity extends ActionBarActivity {
private ImageButton cbButton;
private int status;
private int checkbox_images[] = {
R.drawable.checkbox_unchecked,
R.drawable.checkbox_checked,
R.drawable.checkbox_error,
R.drawable.checkbox_partly
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = 0;
addListenerToButton();
}
private void addListenerToButton(){
cbButton = (ImageButton) findViewById(R.id.ibtnCheckbox);
cbButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
switch(status){
// Unchecked -> Green checked
case 0:
// Green checked -> Red cross
case 1:
// Red cross -> Orange-yellow checked
case 2:
cbButton.setImageResource(checkbox_images[++status]);
break;
// Orange-yellow checked -> Unchecked
case 3:
cbButton.setImageResource(checkbox_images[status = 0]);
break;
// Default (just in case)
default:
status = 0;
cbButton.setImageResource(checkbox_images[status++]);
break;
}
}
});
}
...
}