Destroy fragment on return

Asked

Viewed 320 times

1

I have a NavigationDrawer with many menus on Navigation all open as fragment, when I open a fragment and return it returns to the home screen and if it comes back again close, blz ta correct.

But if you open a fragment A from the menu and when this fragment A is open and choose another fragment B it will open too, but when it comes back it does not return to the home screen, it returns to fragment A and then to the home screen.

I would like it independent of the fragment open and when clicked on the button back of the cell phone it returned to the home screen and then when coming back again it close the application.

code of onNavigationItemSelected

public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_inicio) {
            meuFragmento = new principal();
            fragmentoSelec = true;
            barra = "Expresso1002";
        } else if (id == R.id.nav_consultar_horarios) {
            meuFragmento = new consultarHorarios();
            fragmentoSelec = true;
            barra = "Horários e Preços";
        } else if (id == R.id.nav_pontos_venda) {
            meuFragmento = new pontosVendas();
            fragmentoSelec = true;
            barra = "Pontos de Vendas";
        } else if (id == R.id.nav_quem_somos) {
            meuFragmento = new quemSomos();
            fragmentoSelec = true;
            barra = "Quem Somos";
       } else if (id == R.id.nav_sair) {
            finish();
       }

       if (fragmentoSelec == true) {

getSupportFragmentManager().beginTransaction().replace(R.id.content_principal, meuFragmento).addToBackStack(null).commit();
        }

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

Code of onBackPressed

public void onBackPressed() {

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        //retornar o drawer
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);

            // retorna todos os fragments que estão em backStack
        } else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
            if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
                //Volta o titulo pra Activity
                toolbar.setTitle("Expresso1002");
            }
        }
        //fecha a aplicação, aqui você pode fazer voltar para alguma activity
        else {
            super.onBackPressed();
        }

    }

1 answer

0


Hello, just clear the Backstack, leaving onBackPressed as follows:

@Override
public void onBackPressed() {
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    //retorna o drawer
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);

        // Independente do fragment que está, retorna pra activity
    } else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        //faz voltar pra activity e limpa o popBackStack
        getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
    //fecha a aplicação, aqui você pode fazer voltar para alguma activity
    else {
        super.onBackPressed();
    }
}

OPTION:

If you are having trouble updating titles creates the following method:

private void updateTitleAndDrawer(Fragment fragment) {
    String flagFragment = fragment.getClass().getName();

    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        //Quando não tiver mais fragment em stack, o titulo da toolbar volta a ser da sua Activity
        toolbar.setTitle("Activity");

    } else if (flagFragment.equals(BlankFragment.class.getName())) {
        //titulo fragment1
        toolbar.setTitle("Fragment1");

    } else if (flagFragment.equals(BlankFragment2.class.getName())) {
        //titulo fragment2
        toolbar.setTitle("Fragment2");
    }
}

And on your Activity’s onCreate add:

        //Sempre que o usuário inicia ou volta o fragmento esse Listener é chamado
        getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
        //recupera o fragment a partir do id em que está no xml da sua activity.
                Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment);

                if (fragment != null){
                    updateTitleAndDrawer(fragment);
                } else {
                    toolbar.setTitle("Activity");
                }
            }
        });
  • 1

    Mano ficou Show, vlw.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.