Skip to content Skip to sidebar Skip to footer

Android - Check Radiobutton Id In A Radiogroup With Linearlayout

Is there any possible way to get the selected radio button in this layout? because rg.getCheckedRadioButtonId() not working on this layout. I can't get each of my radiobuttons ID

Solution 1:

Check this answer i have done in my studio, hope this helps,

publicclassStackOneextendsAppCompatActivity {

    private RadioButton rb1, rb2, rb3, rb4;
    private RadioGroup rg;
    privateStringselectedType="";

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.stack_one);

        rb1 = (RadioButton) findViewById(R.id.rad1);
        rb2 = (RadioButton) findViewById(R.id.rad2);
        rb3 = (RadioButton) findViewById(R.id.rad3);
        rb4 = (RadioButton) findViewById(R.id.rad4);
        rg = (RadioGroup) findViewById(R.id.rg);

        GetSelectedRadioButton();
    }

    privatevoidGetSelectedRadioButton() {

        rg.setOnCheckedChangeListener(newRadioGroup.OnCheckedChangeListener() {
            @OverridepublicvoidonCheckedChanged(RadioGroup group, int checkedId) {

                switch (group.getCheckedRadioButtonId()) {
                    case R.id.rad1:
                        selectedType = "rButton1";
                        rb1.setChecked(true);
                        Toast.makeText(StackOne.this,"Radiobutton 1 checked",Toast.LENGTH_LONG).show();
                        break;
                    case R.id.rad2:
                        selectedType = "rButton2";
                        rb2.setChecked(true);
                        Toast.makeText(StackOne.this,"Radiobutton 2 checked",Toast.LENGTH_LONG).show();
                        break;
                    case R.id.rad3:
                        selectedType = "rButton2";
                        rb3.setChecked(true);
                        Toast.makeText(StackOne.this,"Radiobutton 3 checked",Toast.LENGTH_LONG).show();
                        break;
                    case R.id.rad4:
                        selectedType = "rButton2";
                        rb4.setChecked(true);
                        Toast.makeText(StackOne.this,"Radiobutton 4 checked",Toast.LENGTH_LONG).show();
                        break;

                }
            }
        });
    }
}

Checkout this for more detail.

Solution 2:

You can get selected radio button by this way

int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);

this will return you the id of selected radio button

Post a Comment for "Android - Check Radiobutton Id In A Radiogroup With Linearlayout"