Button key return button during fragments

Actually the problem is that I am just loading a fragment ( let call be Fragment-A ). Now fragment-A causes fictitious activity and boot activity of Dummy Activity Fragment-B from the navigation box, than fragment-B, calls Fragment C , and fragment-C calls Fragment-D ..

General image above:

Fragment-A (call) → Dummy Activity (load) → fragment-B (call) → fragment-C (call) → fragment-D (call)

Now I have some question about this:

  • There is actually one button in Fragment D, when the button is called, I need to go back to Fragment-A
  • now While loading a fragment (B, C & D) I have to process On Back Click. means that if the user in fragment D, than on the back press than Fragment-C, loads and vice versa, but when the user is on Fragemnt-B, the On-back key is called, than Fragment A is load

NOTE.

  • I need to handle both Above Back and System Back Key

  • I know that I need to support Fragment Stack, but how can I pass case one

    enter image description here

enter image description here

Edit:

  • In fact, fragment-A is part of the action - (a), and remaging Fragmnets (B, C & D) is part of Activity- (X)

code:

Repo Link: Code Link

+5
source share
2 answers

The above scenario can be resolved below.

  @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { finish(); } 

If the button in fragment D is called, call the getActivity () onBackPresses () function. It will complete the current activity.

0
source

You need to add fragments to the backstack as follows: -

 FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.content_frame, fragmentA); //No need to put fragment A in backstack ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.content_frame, fragmentB); ft.addToBackStack(null); ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.content_frame, fragmentC); ft.addToBackStack(null); ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.content_frame, fragmentD); ft.addToBackStack(null); ft.commit(); 

Now all your fragments are in the back of the screen, therefore, if you click "Back on the fragment", then the fragment "C" will be shown and after clicking "Back" in the fragment C, fragment B will be shown, and when you click "Back" in the fragment B will display fragment A.

AS, you mentioned that you have a special button in fragment D, which when pressed should take you to fragment A, so when you click this button, execute this code: -

 FragmentManager fm = getActivity().getSupportFragmentManager(); for(int i = 0; i < fm.getBackStackEntryCount(); ++i) { fm.popBackStack(); } 
0
source

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


All Articles