- Managing the Fragment Back Stack
- Fighting the framework
- One solution: manage the backstack yourself
- Working with the Framework
- Tags and names
- The back stack tag solution
- Inclusive vs Exclusive
- Полный список
- Android Fragment Back Stack Example
- 1. Fragment Back Stack Example.
- Android Fragments BackStack Tutorial With Example Programmatically
- Download Source Code For Android Fragments Example
- Step 1: Create a new project in Android Studio.
- Step 2: Creating Two Fragments
- Step 3: Making BackStack Activity
- Step 4: Description of BackStackActivity
- Step 5: Updating MainActivity
- Step 6: Description of MainActivity
- Kotlin Version
- 2 thoughts on “Android Fragments BackStack Tutorial With Example Programmatically”
Managing the Fragment Back Stack
Jun 1, 2016 · 3 min read
Or: A lesson in not fighting the framework
The Android framework provides simple APIs for managing your back stack without headache for most simple applications. However at some point you are likely going to run into a situation that doesn’t quite fit the mold of a an application with a simple back stack.
Take, for example, an app that uses bottom navigation. If we start on Tab 1, drill down to a sub screen, then switch to Tab 2, we may want to pop off all the subscreens on Tab 1 before switching to the second tab.
If y ou want to jump right to the sample code, you can find it here on GitHub.
Fighting the framework
In Advocating Against Android Fragments, Pierre-Yves Ricau teaches an important lesson- there’s nothing particularly magical about the Android framework’s back stack. You can manage the back navigation of your application however you want, with or without the framework.
This is true, and you shouldn’t be afraid to manage the back stack yourself if the framework simply isn’t going to work in your scenario. Before you do that, however, make sure you understand the framework and how it can work for you.
One solution: manage the backstack yourself
Here is one way to handle popping off a certain subset of the backstack yourself by keeping track of how many “subscreens” are on the stack:
When I used this approach, I ran into a few quirks that I didn’t like.
First and foremost, it isn’t flexible. What if you add another “level” of back stack management into your app? Then you need to keep track of that too. Going back partway through the stack isn’t particularly easy with this approach.
The other quirk I didn’t like with this approach was that when calling popBackStackImmediate() in succession , each intermediate Fragment is resumed very briefly. This resulted in some code executing for a Fragment that wasn’t visible and wasn’t going to be visible.
Working with the Framework
As it turns out, the Android framework offers a solution that works very well for this and many other situations.
When adding a Fragment to the back stack, Android developers most commonly use addToBackStack(null). Why do we always pass in null? It turns out we can pass in something else that makes the Fragment back stack much more useful.
Tags and names
Fragment transactions can involve two different types of tags. The one that most Android developers are familiar with is the Fragment tag, which you can use to find a specific Fragment in your FragmentManager later via findFragmentByTag(). This is useful for finding a Fragment when your application is in a particular state, but keep in mind that the Fragment needs to be added to your FragmentManager. If you have removed() or replaced() a Fragment and haven’t added it to the backstack, you won’t be able to find it.
The other type of tag is the BackStackRecord’s name passed in to addToBackStack(). This name identifies a particular back stack record, which is a record of what occurred in a particular transaction. popBackStackImmediate() and its counterparts have variants that accept a back stack record name to pop the back stack to a particular state.
The back stack tag solution
Here’s how to solve our problem with back stack tags. I’m actually just going to be using one tag, which identifies the current “first level” Fragment (tab) on the stack.
With this code, the back stack just manages itself! We don’t need to tell it to pop are the right time or keep track of what Fragments we have added.
Inclusive vs Exclusive
There’s one last thing to note in my example, and that’s the use of FragmentManager.POP_BACK_STACK_INCLUSIVE. This tells the FragmentManager to pop our root Fragment state along with everything else. In my example this means that the current tab also gets popped off, creating a clean slate for the new tab we are about to display.
The other option is to pass in zero, which will pop everything up to the specified state. In my example this would leave the current tab on the backstack, so hitting back after navigating to a tab would bring you back to the previous tab.
Источник
Полный список
— динамически работаем с фрагментами
Размещать статические фрагменты мы уже умеем. Но, ясно дело, что гораздо интереснее работать с ними динамически. Система позволяет нам добавлять, удалять и заменять фрагменты друг другом. При этом мы можем сохранять все эти манипуляции в BackStack и кнопкой Назад отменять. В общем, все удобно и красиво.
Создадим простое приложение с двумя фрагментами, которое будет уметь:
— добавлять первый фрагмент
— удалять первый фрагмент
— заменять первый фрагмент вторым фрагментом
— переключать режим сохранения в BackStack операций с фрагментами
Project name: P1051_FragmentDynamic
Build Target: Android 4.1
Application name: FragmentDynamic
Package name: ru.startandroid.develop.p1051fragmentdynamic
Create Activity: MainActivity
В strings.xml добавим строки:
Создаем фрагменты. Как мы помним из прошлого урока, для этого нам нужны будут layout-файлы и классы, наследующие android.app.Fragment
Все почти аналогично прошлому уроку, только убрали вызовы кучи lifecycle методов с логами.
Рисуем основное Activity.
Три кнопки для добавления, удаления и замены фрагментов. Чекбокс для включения использования BackStack. И FrameLayout – это контейнер, в котором будет происходить вся работа с фрагментами. Он должен быть типа ViewGroup. А элементы Fragment, которые мы использовали на прошлом уроке для размещения фрагментов, нам не нужны для динамической работы.
В onCreate создаем пару фрагментов и находим чекбокс.
В onClick мы получаем менеджер фрагментов с помощью метода getFragmentManager. Этот объект является основным для работы с фрагментами. Далее, чтобы добавить/удалить/заменить фрагмент, нам необходимо использовать транзакции. Они аналогичны транзакциям в БД, где мы открываем транзакцию, производим операции с БД, выполняем commit. Здесь мы открываем транзакцию, производим операции с фрагментами (добавляем, удаляем, заменяем), выполняем commit.
Итак, мы получили FragmentManager и открыли транзакцию методом beginTransaction. Далее определяем, какая кнопка была нажата:
если Add, то вызываем метод add, в который передаем id контейнера (тот самый FrameLayout из main.xml) и объект фрагмента. В итоге, в контейнер будет помещен Fragment1
если Remove, то вызываем метод remove, в который передаем объект фрагмента, который хотим убрать. В итоге, фрагмент удалится с экрана.
если Replace, то вызываем метод replace, в который передаем id контейнера и объект фрагмента. В итоге, из контейнера удалится его текущий фрагмент (если он там есть) и добавится фрагмент, указанный нами.
Далее проверяем чекбокс. Если он включен, то добавляем транзакцию в BackStack. Для этого используем метод addToBackStack. На вход можно подать строку-тэг. Я передаю null.
Ну и вызываем commit, транзакция завершена.
Давайте смотреть, что получилось. Все сохраняем, запускаем приложение.
появился первый фрагмент.
Еще раз добавим первый фрагмент – жмем Add. И жмем Replace
первый фрагмент заменился вторым.
Жмем кнопку Назад. Приложение закрылось, т.к. все эти операции с фрагментами не сохранялись в BackStack. Давайте используем эту возможность.
Снова запускаем приложение и включаем чекбокс add to Back Stack
Выполняем те же операции: Add, Remove, Add, Replace. У нас добавится первый фрагмент, удалится первый фрагмент, добавится первый фрагмент, заменится вторым. В итоге мы снова видим второй фрагмент. Теперь жмем несколько раз кнопку Назад и наблюдаем, как выполняются операции, обратные тем, что мы делали. Когда транзакции, сохраненные в стеке закончатся, кнопка Назад закроет приложение.
Т.е. все достаточно просто и понятно. Скажу еще про пару интересных моментов.
Я в этом примере выполнял всего одну операцию в каждой транзакции. Но, разумеется, их может быть больше.
Когда мы удаляем фрагмент и не добавляем транзакцию в BackStack, то фрагмент уничтожается. Если же транзакция добавляется в BackStack, то, при удалении, фрагмент не уничтожается (onDestroy не вызывается), а останавливается (onStop).
В качестве самостоятельной работы: попробуйте немного изменить приложение и добавлять в один контейнер сразу два фрагмента. Возможно, результат вас удивит )
На следующем уроке:
— рассмотрим взаимодействие между Activity и ее фрагментами
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Android Fragment Back Stack Example
Android OS provides a back stack function for Activity, it also provides the back stack function for Fragment. If you add one Fragment into the back stack, when you press the android device back menu, you can find the Fragment that is saved in the back stack popup. Until all the saved Fragments in the back stack popup, then the activity will exit.
1. Fragment Back Stack Example.
- This example contains one activity and three fragments.
- Each fragment includes a button and an input text box.
- When clicking the button it will either show a hidden or create a new target fragment.
- When clicking the back menu, the stacked fragments will be popup by order, if the fragment is hidden in the stack ( fragment two ), then the text in the input box will be saved also.
- If the fragment is replaced in the stack ( fragment one ), because the replace action will delete the previous fragment ( fragment one ) and then add a new fragment ( fragment two ), so the input text in the previous fragment will not be saved.
- You can use the below code to put a fragment into the back stack.
- If you click the “Go To Fragment One” button in Fragment three, because Fragment one is at the bottom of the back stack, so it will remove all the above Fragments in the back stack and show Fragment One again.
- So when you go to Fragment Two again, you will find the input text disappear because it is newly created.

Источник
Android Fragments BackStack Tutorial With Example Programmatically
Hello, all. Welcome to Android Fragments tutorial for beginners.
In Android fragments example, you will learn how to create a basic fragment with a simple example and source code.
You will learn how to create maintain multiple fragments in one activity.
We will see how to handle and manage backstack of fragments.
Android Studio will be used to make android fragments tutorial with example.
First, check the output of Android fragments example, then we will develop it.

Download Source Code For Android Fragments Example
Step 1: Create a new project in Android Studio.
Make a new project in android studio. Consider a main activity as empty activity.
Step 2: Creating Two Fragments
Make two new fragments and give them name as “OneFragment” and “TwoFragment.”
Add below code in OneFragment.java
Paste following source code in fragment_one.xml
Add below code in TwoFragment.java
Copy following in fragment_two.xml
Step 3: Making BackStack Activity
Create a new activity named “BackStackActivity.”
Copy following in activity_back_stack.xml
Add below in BackStackActivity.java
Step 4: Description of BackStackActivity
Below method is used to create a fragment.
In the second parameter, a boolean variable “addToBackStack” is passed.
If addToBackStack is true then, the fragment will be saved in back stack. That means when a user clicks on the back button all the fragments present in backstack will be set in container_frame as per its order.
Step 5: Updating MainActivity
Add below to activity_main.xml
Add following in MainActivity.java
Step 6: Description of MainActivity
Following method is used to open fragment.
Same as in BackStackActivity, a boolean addToBackStack variable is passed in the second parameter.
Here it is false, so if a user clicks back button, the app will be closed because nothing was saved in the backstack.
Kotlin Version
So that is all for Fragments Android example.
Feel free to comment your queries and reviews in the comment section. Thank you.
2 thoughts on “Android Fragments BackStack Tutorial With Example Programmatically”
is there any way when click on button 2 that open google maps avoid that the fragment open the google maps oncreate everytime? Im asking because Im doing something exactly like yours example, fragment 1 will be one screen to user choose some options and when user clique um button calls other fragment, I’ve done it, everything is working well, but everytime I call the second fragment with google maps, I see that google maps on create is been fired each time, doing this google is asking 10 times if the user comeback to filter fragment, Im trying to avoid this, any idea?
Источник