How to handle backPress with snippet

I have Fragment activity using the contatin navigation container. After clicking on the element of the navigation element, fragment 1, fragment 2, Fragment 3 opens, and then after the event of pressing the button in Fragment 1, we open a new fragment 4.

I need to return to a keystroke, how can I do this on Fragment 4? after pressing a key in Fragment 4 I want to return Fragment 1.

enter image description here

+6
source share
3 answers

Add snippets to BackStack. Before commit () a transaction, use the addToBackStack () method i.e.

addToBackStack("Some String").commit(); 

and in onBackPressed ()

 @Override public void onBackPressed() { if (getSupportFragmentManager().getBackStackEntryCount() > 0) { getSupportFragmentManager().popBackStack(); } else { this.finish(); } } 
+19
source

Your code for adding a snippet to backstack should look like this:

 getFragmentManager() .beginTransaction() .replace(R.id.content_frame, Entry_Account.newInstance(), Entry_Account.TAG).addToBackStack("Some string") .commit(); 

Then, in On Activity onBackPressed mode, use this snippet:

 @Override public void onBackPressed () { if(getFramentManager().getBackStackEntryCount()>0){ // popback statck. } else{ // finish your activity. } } 
+5
source

Override the onBackPress () method and make sure your fragement manager has a backStack> 0 entry if it is greater than 0 than the popback stack, otherwise it will terminate your activity.

 if(getFramentManager().getBackStackEntryCount()>0){ // popback statck. } else{ // finish your activity. } 

Remember to add your reflection to BackStack to support the fragment hierarchy.

 fragTransacion.addToBackStack(TAG); 
+4
source

Source: https://habr.com/ru/post/980348/


All Articles