Android: how to group buttons?

Asked

Viewed 164 times

2

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

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

Thank you.

1 answer

1


There is no component that does this for you similar to RadioGroup. You have 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 state 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);
}
  • Thank you!.. a question, the "setOnClickListener" where would you put it? Inside the Oncreate()?

  • @porthfind this, soon after instantiating its components

  • I put in xml the android command:onClick="onClick" on each button and dp in Java have there a method onClick...n know if it is correct to do so mt, but I do not think it is correct to put in onCreate()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.