android onCheckedChanged for radiogroup

前端 未结 6 1611
死守一世寂寞
死守一世寂寞 2021-01-07 16:39

I\'m writing an Activity in android where I have two radio buttons under a RadioGroup. One of them is checked by default. But I can\'t trigger the event in

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 17:36

    The problem is because, you are setting OnCheckedChangeListener on RadioGroup after the providerRadio.performClick(); method call.

    That's why when providerRadio.performClick(); method executes till then their is no OnCheckedChangeListener available to call. So, to make it work, you need to set Listener before the call to performClick() method.

    And instead of using RadioButton.performClick() you should use RadioGroup.check() method to change the current checked RadioButton.

    So you can use this code to change current selection of RadioGroup

    RadioGroup ItemtypeGroup = (RadioGroup) findViewById(R.id.rechargeItemtype);
    ItemtypeGroup
            .setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    Log.d("chk", "id" + checkedId);
    
                    if (checkedId == R.id.a) {
                        //some code
                    } else if (checkedId == R.id.b) {
                        //some code
                    }
    
                }
    
            });
    ItemtypeGroup.check(R.id.a);
    

    Note:- Make sure to call RadioGroup.check() method after adding OnCheckedChangeListener as above in code snippet.

提交回复
热议问题