keep android button selected state

I searched on Google and found this Stack Overflow post:
How can i keep one button as pressed after click on it?

mycodes_Button.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mycodes_Button.setPressed(true);
        return true;
    }
});

But read the comment, it's pretty interesting!


I know I'm late to the party but I tried doing the above and it was still acting like a temporary state (unless you want to keep your finger on it).

What worked for me is to have state_selected="true" in the XML file + imageButton.setSelected(true) in my java file. see below.

ibType1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
    ibType1.setSelected(true);
    ibType2.setSelected(false);
}//onClick
});

XML:

<item android:state_selected="true">
<shape android:shape="rectangle">
    <corners android:radius="45dp" />
    <solid android:color="@color/colorAccent" />
    <stroke android:width="1dp" android:color="#000000"/>
</shape>

This will allow you to have image buttons or button with a specific background state selected programmatically up until you decide to selected another image button or button.


Here's a thought, disable the pressed button and enable the others. Have the disabled button layout similar to the pressed layout. The user will see it as pressed, but it's actually disabled.


Why are you using Buttons? CheckBox or RadioGroup is best solution for these case

checkBox.setChecked(false);

Tags:

Android

Button