Why does turning the device (from portrait to landscape or vice versa) close the fragment in which I am currently?

4

Good morning.

I have a Activity that is a DrawerMenu (side menu), from which I make calls to different fragments, the problem I have is that when I access a Fragment and turn the device, it closes the Fragment and return me to the main activity. How could I solve this situation? Thank you in advance.

This is the activity of the drawer menu (lateral menu):

    public class LeftMenuActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener ,SimpleDialog.OnSimpleDialogListener{

    private TextView lblUserN;
    private TextView userEmail;
    private LinearLayout linearMenuLeft;
    private NavigationView navigationView;
    private Menu menuNav;
    private Global global;
    private int totalFacilitiesFavorites;
    private ArrayList<Facility> facilitiesFavorites;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_left_menu);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        global = new Global();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();


        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //seleccionamos por defecto la primera opcion del menu
        navigationView.getMenu().getItem(0).setChecked(true);
        onNavigationItemSelected(navigationView.getMenu().getItem(0));
        View header=navigationView.getHeaderView(0);

        lblUserN =(TextView) header.findViewById(R.id.lblUserN);
        userEmail =(TextView) header.findViewById(R.id.userEmail);
        linearMenuLeft =(LinearLayout) header.findViewById(R.id.linearMenuLeft);

        //recuperar datos de session
        SharedPreferences prefs = this.getSharedPreferences("login_data",   Context.MODE_PRIVATE);
        String realName = prefs.getString("realName", "");
        String profilePicture = prefs.getString("profilePicture", "");
        String email = prefs.getString("email", "");

        menuNav = navigationView.getMenu();

    }



    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }
        if (getFragmentManager().getBackStackEntryCount() > 0) {
            getFragmentManager().popBackStack();
        } else {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            }else{
                super.onBackPressed();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        return true;
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        FragmentManager fragmentManager = getSupportFragmentManager();

        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.searchItem) {
            closeOtherFragments();
            fragmentManager.beginTransaction().replace(R.id.content_frame,new SearchFragment()).commit();

        } else if (id == R.id.loginItem) {
            closeOtherFragments();
            getSupportFragmentManager().beginTransaction().replace(R.id.content_login,new LoginFragment()).commit();

        } else if (id == R.id.logout) {
            //destruimos los datos de la session
            destroySession();
            MenuItem loginItemMenu = menuNav.findItem(R.id.loginItem);
            loginItemMenu.setVisible(true);

            //refrescamos la activity actual
            global.refreshActualActivity(this);

        } else if (id == R.id.reviewsItem) {
            closeOtherFragments();
            getSupportFragmentManager().beginTransaction().replace(R.id.content_facility_reviews,new UserReviewsFragment()).commit();

        } else if (id == R.id.favoritesItem) {
            closeOtherFragments();
            getSupportFragmentManager().beginTransaction().replace(R.id.content_facility_favorite,new FacilityFavoriteFragment()).commit();
        }
        else if (id == R.id.toursItem) {
            closeOtherFragments();
            getSupportFragmentManager().beginTransaction().replace(R.id.content_facility_tours,new FacililityToursFragment()).commit();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    @Override
    public void onPossitiveButtonClick() {

    }

    @Override
    public void onNegativeButtonClick() {

    }
}

Turning the device I noticed that the oncreate of this Activity is executed again.

    
asked by devjav 13.12.2016 в 20:40
source

2 answers

3

This happens because when you rotate the device the Activity is destroyed and when you create it again at the beginning it does not have a Fragment by default, inside onCreate() it should have which is the Fragment that was originally made.

A quick solution would be to add the following property to your Activity within AndroidManifest.xml :

<activity
            ...
            ...
            android:configChanges="orientation|keyboardHidden|screenSize">

This works but sometimes the destruction of the Activity is required because our application requires it, therefore this does not apply anymore. Therefore another solution is to know that Fragment is the last loaded and within onCreate() perform the transaction:

  public void onCreate(Bundle savedInstanceState) {
        ...
        ...
       if (savedInstanceState == null) {
          //Realiza la transacción del Fragmento el cual mediante preferencias podemos determinar cual fue el último.
          Fragment fragment = new new myFragment();


          //Realizamos la transacción del Fragmento al iniciar la Activity.
          FragmentManager manager = getSupportFragmentManager();
          FragmentTransaction ft = manager.beginTransaction();
          ft.replace(R.id.container, fragment);
          ft.commit();
       }
}
    
answered by 13.12.2016 / 21:04
source
1

Some device configurations may change during runtime (such as the orientation of the screen). When these changes occur, Android restarts the Activity running (called onDestroy() and then% onCreate() ).

In the documentation Android explains a little about the process you must follow to control the Orientation or configuration changes.

To solve this and capture the configuration changes you can do the following:

Manifest

In it you can declare the changes you want to control using the android tag: configChanges, leaving the declaration of the activity as follows:

<activity
     android:name=".MainActivity"
     android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize"
     android:label="@string/app_name"
     android:theme="@style/AppThemeAction" />

Activity

You can put a code to collect the configuration change events such as changing the orientation of the screen and you can perform operations if desired, the code is as follows:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    //detectamos el cambio de orientación en este caso
    if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        landscape = true;
        //acciones deseadas
    }

    if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        landscape = false;
        //acciones deseadas
    }
}
    
answered by 13.12.2016 в 20:58