Android: how to group buttons?

2

Hello, in my application I have a textview with a question and then I have 3 buttons which are the possible options for the answer.

Can anyone tell me how I can group these 3 buttons to have a sort of Group Buttons, is there any way I can do this? (if they were radio buttons would use RadioGroup as container, but for normal buttons is there any way to do it?)

Thank you.

    
asked by anonymous 16.03.2015 / 17:43

1 answer

1

There is no component that does this for you similar to RadioGroup . You need to do this via code, something like:

...
firstButton.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View v) {
            changeButtonState(true, false, false);
        }
});
secondButton.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View v) {
            changeButtonState(false, true, false);
        }
});

thirdButton.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View v) {
            changeButtonState(false, false, true);
        }
});
...

And to change the status of your Button :

private void changeButtonState(boolean first, boolean second, boolean third) {
    // caso você queira alterar a cor do botao selecionado
    if (first) {
        firstButton.setColorFilter(R.color.yourColor);
        secondButton.setColorFilter(R.color.yourColor2);
        thirdButton.setColorFilter(R.color.yourColor2);
    } else if (second) {
        firstButton.setColorFilter(R.color.yourColor2);
        secondButton.setColorFilter(R.color.yourColor);
        thirdButton.setColorFilter(R.color.yourColor2);
    } else {
        firstButton.setColorFilter(R.color.yourColor2);
        iBtnRatingMedium.setColorFilter(R.color.yourColor2);
        thirdButton.setColorFilter(R.color.yourColor);
    }

    firstButton.setSelected(first);
    secondButton.setSelected(second);
    thirdButton.setSelected(third);
}
    
17.03.2015 / 15:42