Addonbackstackchangedlistener android что это

Содержание
  1. Multiple back stacks
  2. A deep dive into what actually went into this feature
  3. The joys of the system back button
  4. Multiple back stacks in Fragments
  5. Paying down our technical debts in Fragments
  6. Реализация правильной обратной навигации и обработки кнопок home с помощью панели инструментов в Android
  7. 6 ответов
  8. «название страницы — изменение заголовков страниц, когда фрагмент в толкнул и выскочил»
  9. «функциональность меню и обратно nav»
  10. «управление гамбургер / кнопка Назад в левом верхнем углу»
  11. FragmentManager
  12. Class Overview
  13. Developer Guides
  14. Summary
  15. Constants
  16. public static final int POP_BACK_STACK_INCLUSIVE
  17. Public Constructors
  18. public FragmentManager ()
  19. Public Methods
  20. public abstract void addOnBackStackChangedListener (FragmentManager.OnBackStackChangedListener listener)
  21. public abstract FragmentTransaction beginTransaction ()
  22. public abstract void dump (String prefix, FileDescriptor fd, PrintWriter writer, String[] args)
  23. public static void enableDebugLogging (boolean enabled)
  24. public abstract boolean executePendingTransactions ()
  25. public abstract Fragment findFragmentById (int id)
  26. public abstract Fragment findFragmentByTag (String tag)
  27. public abstract FragmentManager.BackStackEntry getBackStackEntryAt (int index)
  28. public abstract int getBackStackEntryCount ()
  29. public abstract Fragment getFragment (Bundle bundle, String key)
  30. public void invalidateOptionsMenu ()
  31. public abstract boolean isDestroyed ()
  32. public abstract void popBackStack ()
  33. public abstract void popBackStack (String name, int flags)
  34. public abstract void popBackStack (int id, int flags)
  35. public abstract boolean popBackStackImmediate (int id, int flags)
  36. public abstract boolean popBackStackImmediate (String name, int flags)
  37. public abstract boolean popBackStackImmediate ()
  38. public abstract void putFragment (Bundle bundle, String key, Fragment fragment)
  39. public abstract void removeOnBackStackChangedListener (FragmentManager.OnBackStackChangedListener listener)
  40. public abstract Fragment.SavedState saveFragmentInstanceState (Fragment f)
  41. Get the latest Android developer news and tips that will help you find success on Google Play.
  42. Hooray!

Multiple back stacks

A deep dive into what actually went into this feature

If a ‘back stack’ is a set of screens that you can navigate back through via the system back button, ‘multiple back stacks’ is just a bunch of those, right? Well, that’s exactly what we’ve done with the multiple back stack support added in Navigation 2.4.0-alpha01 and Fragment 1.4.0-alpha01!

The joys of the system back button

Whether you’re using Android’s new gesture navigation system or the traditional navigation bar, the ability for users to go ‘back’ is a key part to the user experience on Android and doing that right is an important part to making your app feel like a natural part of the ecosystem.

In the simplest cases, the system back button just finishes your activity. While in the past you might have been tempted to override the onBackPressed() method of your activity to customize this behavior, it is 2021 and that is totally unnecessary. Instead, there are APIs for custom back navigation in the OnBackPressedDispatcher . This is actually the same API that FragmentManager and NavController already plug into.

That means when you use either Fragments or Navigation, they use the OnBackPressedDispatcher to ensure that if you’re using their back stack APIs, the system back button works to reverse each of the screens that you’ve pushed onto the back stack.

Multiple back stacks doesn’t change these fundamentals. The system back button is still a one directional command — ‘go back’. This has a profound effect on how the multiple back stack APIs work.

Multiple back stacks in Fragments

At the surface level, the support for multiple back stacks is deceptively straightforward, but requires a bit of an explanation of what actually is the ‘fragment back stack’. The FragmentManager ’s back stack isn’t made up of fragments, but instead is made up of fragment transactions. Specifically, the ones that have used the addToBackStack(String name) API.

This means when you commit() a fragment transaction with addToBackStack() , the FragmentManager is going to execute the transaction by going through and executing each of the operations (the replace , etc.) that you specified on the transaction, thus moving each fragment through to its expected state. FragmentManager then holds onto that transaction as part of its back stack.

When you call popBackStack() (either directly or via FragmentManager ’s integration with the system back button), the topmost transaction on the fragment back stack is reversed — an added fragment is removed, a hidden fragment is shown, etc. This puts the FragmentManager back into the same state that it was before the fragment transaction was initially committed.

Note: I cannot stress this enough, but you absolutely should never interleave transactions with addToBackStack() and transactions without in the same FragmentManager : transactions on your back stack are blissfully unaware of non-back stack changing fragment transactions — swapping things out from underneath those transactions makes that reversal when you pop a much more dicey proposition.

This means that popBackStack() is a destructive operation: any added fragment will have its state destroyed when that transaction is popped. This means you lose your view state, any saved instance state, and any ViewModel instances you’ve attached to that fragment are cleared. This is the main difference between that API and the new saveBackStack() . saveBackStack() does the same reversal that popping the transaction does, but it ensures that the view state, saved instance state, and ViewModel instances are all saved from destruction. This is how the restoreBackStack() API can later recreate those transactions and their fragments from the saved state and effectively ‘redo’ everything that was saved. Magic!

Читайте также:  Android как универсальный пульт управления

This didn’t come without paying down a lot of technical debt though.

Paying down our technical debts in Fragments

While fragments have always saved the Fragment’s view state, the only time that a fragment’s onSaveInstanceState() would be called would be when the Activity’s onSaveInstanceState() was called. To ensure that the saved instance state is saved when calling saveBackStack() , we need to also inject a call to onSaveInstanceState() at the right point in the fragment lifecycle transitions. We can’t call it too soon (your fragment should never have its state saved while it is still STARTED ), but not too late (you want to save the state before the fragment is destroyed).

This requirement kicked off a process to fix how FragmentManager moves to state to make sure there’s one place that manages moving a fragment to its expected state and handles re-entrant behavior and all the state transitions that go into fragments.

35 changes and 6 months into that restructuring of fragments, it turned out that postponed fragments were seriously broken, leading to a world where postponed transactions were left floating in limbo — not actually committed and not actually not committed. Over 65 changes and another 5 months later, and we had completely rewritten most of the internals of how FragmentManager manages state, postponed transitions, and animations. That effort is covered in more detail in my previous blog post:

Источник

Реализация правильной обратной навигации и обработки кнопок home с помощью панели инструментов в Android

Я использую одно действие и несколько фрагментов(скриншот прилагается) в пределах одного действия, чтобы обеспечить плавную навигацию. Но после внедрения последней панели инструментов и навигационного представления, кажется, трудно обрабатывать кнопки навигации и дома. У меня проблемы со следующими вещами.

  • управление кнопкой гамбургер / назад в левом верхнем углу. Переключение значка и функциональности в меню и обратно nav.
    • заголовок страницы-изменение заголовков страниц всякий раз, когда осколок в толчке и хлопнул.

Я пробовал несколько вещей, таких как переопределение onBackPressed (), setHomeAsUpIndicator, всплывающие фрагменты вручную. Раньше я использовал переключатель ActionBarDrawer для обработки этого, но сейчас он как-то не работает. Я проверил образцы google, они, похоже, используют отдельные действия в большинстве мест.

может ли кто-нибудь указать мне, как реализовать правильную обратную навигацию для обработки кнопки NavigationView, Back в внутренние фрагменты и названия страниц? Я использую AppCompatActivity, android.приложение.Фрагмент, NavigationView и панели инструментов.

Fragment 2 -> Fragment 3″ src=»https://askdev.ru/images/content/36566726/d0fd3d02a984297ed25a59cb9568215c.jpg»>

6 ответов

это гораздо проще проиллюстрировать с каким-то разделением ответственности за ваш Activity и Fragment .

Проблема 1: управление кнопкой гамбургер / назад в левом верхнем углу. Переключение значка и функциональности в меню и обратно nav.

на иллюстрации решение должно быть инкапсулировано с помощью Activity , который будет выглядеть примерно так:

Проблема 2: Название страницы — Изменение заголовков страниц всякий раз, когда фрагмент в толкнул и выскочил.

по существу, это можно обработать в onStart для каждого Fragment т. е. ваш ListFragment, DetailsFragment и CommentsFragment выглядят примерно так:

наверное стоит setRetainInstance(true) на onCreate ваши фрагменты.

Это действительно распространенная проблема, которую я преодолел, создав своего рода проект шаблона, который я использую, когда начинаю новый проект Android. Идея состоит в том, чтобы абстрагировать столько логики, которая обрабатывает кнопку «Назад», индикатор «гамбургер» и управление фрагментами в многоразовые классы:

начните с создания класса BaseActivity и BaseFragment. Это где вы собираетесь столько кода, как это возможно.

давайте начнем с вашей BaseActivity

FragmentManager является ключом к владению задним стеком, поэтому вам нужно прослушать изменения в заднем стеке отсюда. AddFramentHandler-это небольшой класс, который я приготовил, чтобы упростить добавление фрагментов из фрагментов. Подробнее об этом позже.

onBackPressed где происходит волшебство. Вы замечаете форматирование обычного текста методов.. Я огромный Код fan-если вам нужно написать комментарии, ваш код не чист. В основном вам нужно действительно иметь центральное место, где вы можете бежать, когда вы не уверены, почему нажатие кнопки назад не происходит так, как вы ожидаете. Этот метод и есть то место.

это другая ключевая часть BaseActivity. В основном этот метод проверяет, находитесь ли вы в корневом фрагменте и соответственно настраивает индикатор. Обратите внимание, что он изменяет прослушиватель в зависимости от того, сколько фрагментов находится в заднем стеке.

тогда есть BaseFragment:

код выше показывает, как заголовок обрабатывается фрагментами.

попробуйте что-то вроде этого:

обрабатывать состояние ящика onBackPressed :

перезагрузка при обратном нажатии всегда добавляйте транзакцию фрагмента в задний стек следующим образом:

чтобы динамически изменить заголовок страницы, вы можете вызвать это из каждого Fragment s onStart или onResume способ:

Примечание: я рассмотрел объявление стандартного макета и, таким образом, я не включил никаких макетов.

«название страницы — изменение заголовков страниц, когда фрагмент в толкнул и выскочил»

когда вы удаляете фрагмент, метод isRemoving() . Это помогает изменить название обратно.

«функциональность меню и обратно nav»

предложение: мы должны полагаться на навигационную систему android по умолчанию. Если мы используем addToBackStack() для наших фрагментов теоретически нам вообще не нужно переопределять onBackPressed ().

  1. » App не переопределяет ожидаемую функцию системного значка (например, кнопки «Назад»).»
  2. «приложение поддерживает стандартную навигацию по системной кнопке «Назад» и не использует никаких пользовательских, экранных подсказок «назад».»
Читайте также:  Как портировать прошивки для андроид

«управление гамбургер / кнопка Назад в левом верхнем углу»

Я предлагаю использовать вместо «MainActivityDetailFragment», чтобы избежать осложнений.

добавьте это в свою MainActivity, где вы вызываете фрагменты. getBackStackEntryCount () возвращает количество фрагментов в заднем стеке. где фрагмент в нижней части стека имеет индекс 0. popBackStack () поп верхний фрагмент из заднего стека

и в вашем фрагменте, куда вы хотите вернуться, используйте эту функцию

хорошо, после многих тестов мне наконец удалось настроить хорошую навигацию. Мне нужно было то же самое, что и вам, единственная разница в том, что я использую фрагменты v4, но я не думаю, что это что-то изменит здесь.

Я не использую ActionBarDrawerToggle поскольку последние примеры из Google больше не используют этот компонент.

Решение ниже также работает для глубокой навигации: родительская активность — > фрагмент —> фрагмент и т. д.

единственное изменение, необходимое в Фрагменты, чтобы изменить название:

в родительской деятельности onCreate метод, я инициализирую следующим образом:

вот теперь код для обработки действия на кнопке Home:

и, наконец, код для обработки действия обратного нажатия:

Источник

FragmentManager

Class Overview

Interface for interacting with Fragment objects inside of an Activity

Developer Guides

For more information about using fragments, read the Fragments developer guide.

Summary

Nested Classes
FragmentManager.BackStackEntry Representation of an entry on the fragment back stack, as created with FragmentTransaction.addToBackStack() .
FragmentManager.OnBackStackChangedListener Interface to watch for changes to the back stack.
Constants
int POP_BACK_STACK_INCLUSIVE Flag for popBackStack(String, int) and popBackStack(int, int) : If set, and the name or ID of a back stack entry has been supplied, then all matching entries will be consumed until one that doesn’t match is found or the bottom of the stack is reached.
Public Constructors
Public Methods

Constants

public static final int POP_BACK_STACK_INCLUSIVE

Flag for popBackStack(String, int) and popBackStack(int, int) : If set, and the name or ID of a back stack entry has been supplied, then all matching entries will be consumed until one that doesn’t match is found or the bottom of the stack is reached. Otherwise, all entries up to but not including that entry will be removed.

Public Constructors

public FragmentManager ()

Public Methods

public abstract void addOnBackStackChangedListener (FragmentManager.OnBackStackChangedListener listener)

Add a new listener for changes to the fragment back stack.

public abstract FragmentTransaction beginTransaction ()

Start a series of edit operations on the Fragments associated with this FragmentManager.

Note: A fragment transaction can only be created/committed prior to an activity saving its state. If you try to commit a transaction after Activity.onSaveInstanceState() (and prior to a following Activity.onStart or Activity.onResume() , you will get an error. This is because the framework takes care of saving your current fragments in the state, and if changes are made after the state is saved then they will be lost.

public abstract void dump (String prefix, FileDescriptor fd, PrintWriter writer, String[] args)

Print the FragmentManager’s state into the given stream.

Parameters
prefix Text to print at the front of each line.
fd The raw file descriptor that the dump is being sent to.
writer A PrintWriter to which the dump is to be set.
args Additional arguments to the dump request.

public static void enableDebugLogging (boolean enabled)

Control whether the framework’s internal fragment manager debugging logs are turned on. If enabled, you will see output in logcat as the framework performs fragment operations.

public abstract boolean executePendingTransactions ()

After a FragmentTransaction is committed with FragmentTransaction.commit() , it is scheduled to be executed asynchronously on the process’s main thread. If you want to immediately executing any such pending operations, you can call this function (only from the main thread) to do so. Note that all callbacks and other related behavior will be done from within this call, so be careful about where this is called from.

Returns
  • Returns true if there were any pending transactions to be executed.

public abstract Fragment findFragmentById (int id)

Finds a fragment that was identified by the given id either when inflated from XML or as the container ID when added in a transaction. This first searches through fragments that are currently added to the manager’s activity; if no such fragment is found, then all fragments currently on the back stack associated with this ID are searched.

Returns
  • The fragment if found or null otherwise.

public abstract Fragment findFragmentByTag (String tag)

Finds a fragment that was identified by the given tag either when inflated from XML or as supplied when added in a transaction. This first searches through fragments that are currently added to the manager’s activity; if no such fragment is found, then all fragments currently on the back stack are searched.

Returns
  • The fragment if found or null otherwise.

public abstract FragmentManager.BackStackEntry getBackStackEntryAt (int index)

Return the BackStackEntry at index index in the back stack; where the item on the bottom of the stack has index 0.

public abstract int getBackStackEntryCount ()

Return the number of entries currently in the back stack.

public abstract Fragment getFragment (Bundle bundle, String key)

Retrieve the current Fragment instance for a reference previously placed with putFragment(Bundle, String, Fragment) .

Parameters
bundle The bundle from which to retrieve the fragment reference.
key The name of the entry in the bundle.
Returns
  • Returns the current Fragment instance that is associated with the given reference.

public void invalidateOptionsMenu ()

Invalidate the attached activity’s options menu as necessary. This may end up being deferred until we move to the resumed state.

public abstract boolean isDestroyed ()

Returns true if the final Activity.onDestroy() call has been made on the FragmentManager’s Activity, so this instance is now dead.

public abstract void popBackStack ()

Pop the top state off the back stack. This function is asynchronous — it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.

public abstract void popBackStack (String name, int flags)

Pop the last fragment transition from the manager’s fragment back stack. If there is nothing to pop, false is returned. This function is asynchronous — it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.

Parameters
name If non-null, this is the name of a previous back state to look for; if found, all states up to that state will be popped. The POP_BACK_STACK_INCLUSIVE flag can be used to control whether the named state itself is popped. If null, only the top state is popped.
flags Either 0 or POP_BACK_STACK_INCLUSIVE .

public abstract void popBackStack (int id, int flags)

Pop all back stack states up to the one with the given identifier. This function is asynchronous — it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.

Parameters
id Identifier of the stated to be popped. If no identifier exists, false is returned. The identifier is the number returned by FragmentTransaction.commit() . The POP_BACK_STACK_INCLUSIVE flag can be used to control whether the named state itself is popped.
flags Either 0 or POP_BACK_STACK_INCLUSIVE .

public abstract boolean popBackStackImmediate (int id, int flags)

Like popBackStack(int, int) , but performs the operation immediately inside of the call. This is like calling executePendingTransactions() afterwards.

Returns
  • Returns true if there was something popped, else false.

public abstract boolean popBackStackImmediate (String name, int flags)

Like popBackStack(String, int) , but performs the operation immediately inside of the call. This is like calling executePendingTransactions() afterwards.

Returns
  • Returns true if there was something popped, else false.

public abstract boolean popBackStackImmediate ()

Like popBackStack() , but performs the operation immediately inside of the call. This is like calling executePendingTransactions() afterwards.

Returns
  • Returns true if there was something popped, else false.

public abstract void putFragment (Bundle bundle, String key, Fragment fragment)

Put a reference to a fragment in a Bundle. This Bundle can be persisted as saved state, and when later restoring getFragment(Bundle, String) will return the current instance of the same fragment.

Parameters
bundle The bundle in which to put the fragment reference.
key The name of the entry in the bundle.
fragment The Fragment whose reference is to be stored.

public abstract void removeOnBackStackChangedListener (FragmentManager.OnBackStackChangedListener listener)

public abstract Fragment.SavedState saveFragmentInstanceState (Fragment f)

Save the current instance state of the given Fragment. This can be used later when creating a new instance of the Fragment and adding it to the fragment manager, to have it create itself to match the current state returned here. Note that there are limits on how this can be used:

  • The Fragment must currently be attached to the FragmentManager.
  • A new Fragment created using this saved state must be the same class type as the Fragment it was created from.
  • The saved state can not contain dependencies on other fragments — that is it can’t use putFragment(Bundle, String, Fragment) to store a fragment reference because that reference may not be valid when this saved state is later used. Likewise the Fragment’s target and result code are not included in this state.
Parameters
f The Fragment whose state is to be saved.
Returns
  • The generated state. This will be null if there was no interesting state created by the fragment.

Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.

Get the latest Android developer news and tips that will help you find success on Google Play.

Hooray!

You have successfully signed up for the latest Android developer news and tips.

Источник

Читайте также:  Эадор сотворение для андроид
Оцените статью