what is the best way to do a button group that can be selected and activate independently?

后端 未结 3 450
无人共我
无人共我 2020-12-31 04:31

I\'m trying to do in android a group of buttons that can be selected and activate only one of them. I need to work with the same logic of a radiogroup and radiobuttons.

3条回答
  •  时光取名叫无心
    2020-12-31 04:42

    You could still use Radio Buttons inside a Radio Group, and attributes to make each radio button look like a button.

    In xml, for each radio button set android:button="@null", so that dots won't be visible. You could add some padding to make it look different.

    In code, set a CheckedChangeListener to your radioGroup, then find the reference to the checkedView (RadioButton) with checkedId. In this example I've just changed the background color of the view, but you could add a different background too. If the radioButton is not null, it means it has already been changed, so I'll set its initial state again.

    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (radioButton != null) {
          radioButton.setBackgroundColor(Color.TRANSPARENT);
          radioButton.setButtonDrawable(0); // removes the image
        }
        radioButton = (RadioButton) group.findViewById(checkedId);
        radioButton.setBackgroundColor(Color.YELLOW);
        radioButton.setButtonDrawable(R.drawable.icon); //sets the image
      }
    });
    

    Hope this helps!

提交回复
热议问题