0

I have an activity with a RadioGroup that has two RadioButtons. The RadioButtons behave like tabs and should create two different fragments, depending on which of the buttons has been clicked. The problem is that the fragments' onCreateView methods are called twice and I can't figure out why.

This is my Activity:

public class MyActivity {

private RadioGroup radioGroup;
private FrameLayout frame;
private RadioButton radio1;
private RadioButton radio2;

private RadioOneFragment radio1Fragment;
private RadioTwoFragment radio2Fragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity_layout);

    radio1 = (RadioButton) findViewById(R.id.radio1);
    radio2 = (RadioButton) findViewById(R.id.radio2);

    radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
                case R.id.radio1:
                    radio1Fragment = new RadioOneFragment();
                    getFragmentManager().beginTransaction()
                            .replace(R.id.radio_frg_container, radio1Fragment)
                            .commit();
                    break;
                case R.id.radio2:
                    radio2Fragment = new RadioTwoFragment();
                    getFragmentManager().beginTransaction()
                            .replace(R.id.radio_frg_container, radio2Fragment)
                            .commit();
                    break;
            }
        }
    });
    if (getIntent().getExtras() != null) {
        radioGroup.check(R.id.radio2);
    } else {
        radioGroup.check(R.id.radio1);
    }
}
}

Any help is greatly appreciated. Thanks.

user3165984
  • 121
  • 2
  • 10

2 Answers2

1

I've found the answer here: RadioGroup calls onCheckChanged() three times

Instead of using radioGroup.check(R.id.radio1) you should simply use radio1.setChecked(true).

Community
  • 1
  • 1
user3165984
  • 121
  • 2
  • 10
0

Try one Fragment object

private RadioOneFragment radio1Fragment;
private RadioTwoFragment radio2Fragment;

instace of

private RadioTwoFragment radioFragment;

and

switch (checkedId) {
                case R.id.radio1:
                    radioFragment = new RadioOneFragment();
                    getFragmentManager().beginTransaction()
                            .replace(R.id.radio_frg_container, radioFragment)
                            .commit();
                    break;
                case R.id.radio2:
                    radioFragment = new RadioTwoFragment();
                    getFragmentManager().beginTransaction()
                            .replace(R.id.radio_frg_container, radioFragment)
                            .commit();
                    break;
            }
user1214083
  • 122
  • 6