سؤال

I've created a RadioGroup with the following RadioButtons with the layout I want to achieve.

Radiobuttons

XML hierarchy:

  • RadioGroup
    • LinearLayout
      • RadioButton
      • RadioButton
    • LinearLayout
      • RadioButton
      • RadioButton
    • RadioButton

Of course this means only 1 RadioButton is still a direct child of the RadioGroup, which means that when I click any of the RadioButtons, the one who was already checked doesn't uncheck.

I'm using a very compact code to obtain the checked RadioButton, if they were direct childs.

RadioGroup rg = (RadioGroup) v.findViewById(R.id.rgTopupValue);
View radioCheckedView = rg.findViewById(rg.getCheckedRadioButtonId());
RadioButton rb = (RadioButton) rg.getChildAt(rg.indexOfChild(radioCheckedView));

Is there a way to solve the problem, without the use of extremely long cases?

هل كانت مفيدة؟

المحلول

Seems like there is no real answer to your question. I don't think there is a real solution. But this might solve your problem (it's a workaround):

    RadioButton rb1, rb2, rb3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    ...
    rb1 = (RadioButton) findViewById(R.id.rb1);
    rb2 = (RadioButton) findViewById(R.id.rb2);
    rb3 = (RadioButton) findViewById(R.id.rb3);

    rb1.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            rb1.setChecked(true);
            rb2.setChecked(false);
            rb3.setChecked(false);
        }
    });

    rb2.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            rb1.setChecked(false);
            rb2.setChecked(true);
            rb3.setChecked(false);
        }
    });

    rb3.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            rb1.setChecked(false);
            rb2.setChecked(false);
            rb3.setChecked(true);
        }
    });
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top