0

I'm a beginner, and I don't understand, please help. I have the NavigationView and several page fragments. The Problem: If I change the orientation to landscape then reset the data it moves to the main screen. How do you solve this problem?

Code MainActivity.Oncreate()

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_main);
   //removed unnecessary codes
    navigationView.setNavigationItemSelectedListener(this);
    transaction.beginTransaction().replace(R.id.container, fragment_main).commit();
}

and void onNavigationItemSelected() of navigationview

switch (item.getItemId())
 {
     case R.id.nav_main :
  transaction.beginTransaction().replace(R.id.container,fragment_main).commit();
         break;
     case R.id.nav_report_category:
         transaction.beginTransaction().replace(R.id.container,fragment_category).commit();
         break;

     case R.id.nav_history:
         transaction.beginTransaction().replace(R.id.container,fragment_history).commit();
         break;
 }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
  • refer http://stackoverflow.com/questions/15313598/once-for-all-how-to-correctly-save-instance-state-of-fragments-in-back-stack – sasikumar Nov 12 '16 at 04:59

1 Answers1

1

You need to implement your savedInstanceState() method. From there you can pull the view in your onCreate method:

public void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        //Restore the fragment's instance
        savedInstanceState.getString("param");
    }
}
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //Save your fragment data here like so...
    outState.putString("param", value);

}

I would also suggest that you read the Android docs regarding the onSavedInstanceState method and how to recreate an Activity here. I would also suggest you read this article: https://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156