Josh Parinussa
Josh Parinussa

Reputation: 643

How to handle back button to go to specific fragment?

I making project with navigation drawer with fragment, the navigation have 3 fragment. I have problem, when i am at third fragment and i pressed back button the app suddenly close, but the one i want to do is the fragment change from third fragment to first fragment. How i can do that ?

This is my MainActivity code :

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    Toolbar toolbar;
    DrawerLayout drawer;
    NavigationView navigationView;
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;
    Fragment fragment = null;
    SessionManager session;
    TextView kode_kt, nama_ketua;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        session = new SessionManager(getApplicationContext());
        session.checkLogin();

        fragmentManager = getFragmentManager();
        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.addDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View header=navigationView.getHeaderView(0);

        kode_kt = (TextView)header.findViewById(R.id.username);
        nama_ketua = (TextView)header.findViewById(R.id.email);
        HashMap<String, String> user = session.getUserDetails();


        kode_kt.setText(user.get(SessionManager.KEY_KODE));
        nama_ketua.setText(user.get(SessionManager.KEY_KETUA));
//        email.setText("Jopa Software House");

        // tampilan default awal ketika aplikasii dijalankan
        if (savedInstanceState == null) {
            fragment = new Monitoring();
            callFragment(fragment);
        }

    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Toast.makeText(getApplicationContext(), "Action Settings", Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

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

        // Untuk memanggil layout dari menu yang dipilih
        if (id == R.id.nav_camera) {
            fragment = new Monitoring();
            callFragment(fragment);
        } else if (id == R.id.nav_gallery) {
            showDialog();
        } else if (id == R.id.nav_send) {
            fragment = new Akun();
            callFragment(fragment);
        }

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

    // untuk mengganti isi kontainer menu yang dipiih
    private void callFragment(Fragment fragment) {
        fragmentTransaction = fragmentManager.beginTransaction();

        fragmentTransaction.remove(fragment);
        fragmentTransaction.replace(R.id.frame_container, fragment);
        fragmentTransaction.commit();
    }

    private void showDialog(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                this);

        // set title dialog
        alertDialogBuilder.setTitle("Keluar Akun");

        // set pesan dari dialog
        alertDialogBuilder
                .setMessage("Anda ingin keluar dari akun?")
                .setIcon(R.mipmap.ic_launcher)
                .setCancelable(false)
                .setPositiveButton("Ya",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // jika tombol diklik, maka akan menutup activity ini
                        session.logoutUser();
                    }
                })
                .setNegativeButton("Tidak",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // jika tombol ini diklik, akan menutup dialog
                        // dan tidak terjadi apa2
                        dialog.cancel();
                    }
                });

        // membuat alert dialog dari builder
        AlertDialog alertDialog = alertDialogBuilder.create();

        // menampilkan alert dialog
        alertDialog.show();
    }

}

Upvotes: 3

Views: 3747

Answers (4)

sushildlh
sushildlh

Reputation: 9056

Use this code in your Activity

@Override
    public void onBackPressed() {
        Fragment  f = getSupportFragmentManager().findFragmentById(R.id.maincontainer);
        if (f instanceof FirstFragment) {
           // do operations

        } else if (f instanceof SecondFragment) {
           // do operations

        }  else if (f instanceof ThirdFragment) {
           // do operations

        }else {
            super.onBackPressed();
        }

    }

and use ....

getSupportFragmentManager().popBackStack();

for removing fragments from your STACK

Upvotes: 1

Jeffy
Jeffy

Reputation: 286

  @Override
public void onBackPressed() {
    // This overrides default behavior for onBackPressed so that it does nothing.
    // This fixes the bug where when you disconnect the watch from wire, and reconnect,
    // the current current fragment will pop out.
    Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
    if (f instanceof CustomFragmentClass) {// do something with f
        ((CustomFragmentClass) f).doSomething();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_holder,new FragmentSample());
transaction.commit();
    }
}

Upvotes: 0

Hetfieldan24
Hetfieldan24

Reputation: 198

When you call fragmentTransaction.replace() for the fragment that you want to return to after you press the Back button, try to add this to backStack, like this:

private void callFragment(Fragment fragment) {
        fragmentTransaction = fragmentManager.beginTransaction();
        if (fragment instanceof Monitoring)
            fragmentTransaction.addToBackStack(null);
        fragmentTransaction.replace(R.id.frame_container, fragment);
        fragmentTransaction.commit();
    }

Upvotes: 0

jonathanrz
jonathanrz

Reputation: 4296

You should add your fragments to backstack when adding them so Android will handle the backstack popping for your.

You can read more here: https://developer.android.com/training/implementing-navigation/temporal.html

So, your code will be the following:

fragmentTransaction.remove(fragment);
fragmentTransaction.replace(R.id.frame_container, fragment);
fragmentTransaction.addToBackStack();
fragmentTransaction.commit();

Upvotes: 0

Related Questions