I know this is a question that has been asked many times before, but I can\'t seem to solve it in my code. I have two buttons, and when one is pressed, I would like to keep
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);
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.
A checkbox could work, but if you're after a UI closer UISegmentedControl
on iOS, which is possible wrapping all the buttons needed in a LinearLayout
, then you could do something along the lines of:
public void onClick( View v ){
if ( v.getID == R.id.btn1 ) {
btn1.setEnabled(false);
btn2.setEnabled(true);
// do stuff
}
else if ( v.getId() == R.id.btn2 ) {
btn2.setEnabled(false);
btn1.setEnabled(true);
// do stuff
}
}
Of course, in your drawable folder, you would add background colour, borders, and other visual stuff for each 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!