android – Select a RadioButton from a RadioGroup, according to a condition

Question:

I have a radiogroup and according to a condition one or the other must be selected. How to make it come up to the screen as described below? Code:

private RadioGroup mSwitchButtonGroup;
private boolean mGoesByCar;
private User user;

    .....
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.fragment_confirm_routine, container, false);
                user = new User();
                mSwitchButtonGroup = (RadioGroup)view.findViewById(R.id.switch_rider_button);

                if (user.hasCar()){
                    mSwitchButtonGroup -> R.id.goes_by_car deve aparecer checked
                }else {
                    mSwitchButtonGroup -> R.id.doesnt_go_by_car deve aparecer checked
                }
    ......

                if(mSwitchButtonGroup!=null){
                    mSwitchButtonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {
                            if(checkedId == R.id.goes_by_car){
                                mGoesByCar = true;
                            }else if(checkedId == R.id.doesnt_go_by_car){
                                mGoesByCar = false;
                            }
                        }
                    });
                }
....

I hope I was clear. Thank you very much in advance!

Answer:

Use the check() method of the RadioGroup class:

if (user.hasCar()){
    mSwitchButtonGroup.check(R.id.goes_by_car);
}else {
    mSwitchButtonGroup.check(R.id.doesnt_go_by_car)
}
Scroll to Top