I implemented a code for closing app from secondary Activity ...but in secondary Activity there are Fragments also and the problem is when I jumped into any Fragment and I pressed back button app directly closes .. my aim is to first Fragment-transaction's addToBackStack
should work then app should close
This is the code in UserActivity's onBackPressed()
method where I implemented Fragments:
public void onBackPressed() {
DrawerLayout drawerLayout = findViewById(R.id.drawerLayout);
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
Intent intent = new Intent(UserActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
}
Below code is in MainActivity's onCreate()
method to finish Activity:
if (getIntent().getBooleanExtra("EXIT",false)) {
finish();
}
and here are Fragments put in UserActivity:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.setting:
fragment = new SettingFragment();
break;
case R.id.logOut:
SharedPreference.setLoggedIn(this,null,false);
Intent intent = new Intent(UserActivity.this,MainActivity.class);
startActivity(intent);
default:
fragment = null;
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.userFragment,fragment).addToBackStack(null).commit();
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}