How to check state Changing of Radio Button android?

自古美人都是妖i 提交于 2020-01-04 09:17:17

问题


i want to check if radioButton is clicked change some value

Here's my code :

new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,"Ok");
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,"Ok");
RadioButton radioButton =
                        new DynamicViews().makeRadioButtonforAnswer(getApplicationContext(),radioGroup,"This is the answer");

The first two radios are created without referencing but the last one is my Answer so i got a reference to check if is checked.

Here my Question : How can i check if the radioButton is ticked?

   radioButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        goToNextLevel = true;
                    }
                });

this is my Approach so far but it does not work perfectly because when users select radioButton and after that will change their choice the value of goToNextLevel does not change and will set to true in the wrong way.

How to find out as long as the radioButton is checked set the goToNextLevel to true and otherwise to false.


回答1:


First create RadioGroup if you didn't do that yet, then as usual connect it by it's id and then use setOnCheckedChangeListener. You can check is your RadioButton checked or not also you can have more then one RadioButton. For example:

radioGroup.setOnCheckedChangeListener(new new OnCheckedChangeListener(){
    @Override
        public void onCheckedChanged(RadioGroup group, int checkedId)
        {
            switch(checkedId)
            {
            case R.id.firstRadioButton:
                //Implement logic
                break;
            case R.id.secondRadioButton:
                //Implement logic
                break;
            }
        }
    });


来源:https://stackoverflow.com/questions/45678797/how-to-check-state-changing-of-radio-button-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!