0

I have an Activity with a FrameLayout to load fragment and a RadioGroup with four radio button. Let's say RadioButton rb1, rb2, rb3, rb4 will load different Fragment F1, F2, F3, F4 respectively on the checkChanged and default it will load F1 fragment.

Now, if i am selecting rb2 then it is loading fragment F2 and after orientation change again it is loading F1. Bellow is my code, please give any suggestion how to handle it.

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

        mRadioWidget = (RadioWidget) findViewById(R.id.segmented_control);
        mRadioWidget.mRGroup.setOnCheckedChangeListener(this);

        if (savedInstanceState == null) {
            HomeFragment homeFragment = new HomeFragment();
            loadFragment(false, homeFragment, HomeFragment.CLASSTAG);
        }
    }

@Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        switch (checkedId) {

        case R.id.rb_home:

            HomeFragment homeFragment = new HomeFragment();
            loadFragment(false, homeFragment, HomeFragment.CLASSTAG);
            break;

        case R.id.rb_config:

            ConfigFragment configFragment = new ConfigFragment();
            loadFragment(false, configFragment, ConfigFragment.CLASSTAG);
            break;

        case R.id.rb_flash:

            Toast.makeText(getApplicationContext(), "Not yet implemented", Toast.LENGTH_LONG).show();
            break;

        case R.id.rb_fav:

            FavoritesFragment favFragment = new FavoritesFragment();
            loadFragment(false, favFragment, FavoritesFragment.CLASSTAG);
            break;
        }
    }
Vid
  • 992
  • 1
  • 11
  • 28

2 Answers2

2

You should try to remember the fragment that was last loaded by putting some sort of a value in the savedInstanceState Bundle.

This is how you can save and retrieve data : Saving Android Activity state using Save Instance State

When in onCreate the bundle is not null, retrieve that value from the bundle, and then load the correct fragment and update the checkbox.

Community
  • 1
  • 1
Shivam Verma
  • 7,825
  • 3
  • 24
  • 32
1

In AndroidManifest file add android:configChanges="orientation|screenSize" in your activity.

Arun Badole
  • 10,779
  • 19
  • 66
  • 94
  • 2
    Adding this to the activity tag will prevent the issue from happening but this is not the way it should be done because this prevents the activity from recreating which leads to other issues such as the correct layout not being set for the landscape mode and all such cases will need to be handled by the developer explicitly in the code. – Shivam Verma Jan 23 '15 at 11:32