Reputation: 73
Hi I am new to android development. I am facing a problem with fragments. Initially, anytime i opened a fragment and hit the back button on the android device, it closes the app until i found a solution which involved the use of fragmentTransaction.addToBackStack(null) method; but my problem is that if i open other fragments from the home fragment and click the home button each time i opened a new fragment, the back button, keeps going back to the previous fragment even after it gets to the home fragment. To explain further lets assume this are my events on the app.
app opens => Home fragment => fragment B => Home fragment => fragment c => fragment D =>Home fragment
when i hit the back button this is what it does:
Home fragment => fragment D => fragment c => Home fragment => fragment B => Home fragment => app closes
I don't like the fact that even after hitting the home fragment, the app continues going back to the fragments before the home fragment.
Please how can i make sure that every time the user gets to the home fragment and presses the back button it cancels all other fragments before it and just closes the app.
I hope i explained this well. please any help would be very helpful. Thank you.
Upvotes: 1
Views: 55
Reputation: 394
Always beware of coding an app that bucks the Android Framework...
Clear Fragment stack:
getSupportFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
Clear Activity stack:
Intent intent = new Intent(Your_Current_Activity.this,
Your_Destination_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
|Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Upvotes: 1
Reputation: 1387
You can try with these two methods in your activity -
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
Upvotes: 0