Навигация

Навигация — это платформа для навигации между «пунктами назначения» в приложении Android, которая предоставляет согласованный API независимо от того, реализованы ли пункты назначения как фрагменты, действия или другие компоненты.
Последнее обновление Стабильный выпуск Кандидат на выпуск Бета-версия Альфа-релиз
12 марта 2025 г. 2.8.9 - - 2.9.0-альфа08

Объявление зависимостей

Чтобы добавить зависимость от навигации, необходимо добавить в свой проект репозиторий Google Maven. Для получения дополнительной информации прочтите репозиторий Google Maven .

Добавьте зависимости для нужных вам артефактов в файл build.gradle для вашего приложения или модуля:

Groovy

plugins {
  // Kotlin serialization plugin for type safe routes and navigation arguments
  id 'org.jetbrains.kotlin.plugin.serialization' version '2.0.21'
}
  
dependencies {
  def nav_version = "2.8.9"

  // Jetpack Compose Integration
  implementation "androidx.navigation:navigation-compose:$nav_version"

  // Views/Fragments Integration
  implementation "androidx.navigation:navigation-fragment:$nav_version"
  implementation "androidx.navigation:navigation-ui:$nav_version"

  // Feature module support for Fragments
  implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

  // Testing Navigation
  androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"

  // JSON serialization library, works with the Kotlin serialization plugin.
  implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3"
}

Kotlin

plugins {
  // Kotlin serialization plugin for type safe routes and navigation arguments
  kotlin("plugin.serialization") version "2.0.21"
}

dependencies {
  val nav_version = "2.8.9"

  // Jetpack Compose integration
  implementation("androidx.navigation:navigation-compose:$nav_version")

  // Views/Fragments integration
  implementation("androidx.navigation:navigation-fragment:$nav_version")
  implementation("androidx.navigation:navigation-ui:$nav_version")

  // Feature module support for Fragments
  implementation("androidx.navigation:navigation-dynamic-features-fragment:$nav_version")

  // Testing Navigation
  androidTestImplementation("androidx.navigation:navigation-testing:$nav_version")

  // JSON serialization library, works with the Kotlin serialization plugin
  implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
}

Безопасные аргументы

Чтобы добавить Safe Args в свой проект, включите следующий classpath в файл build.gradle верхнего уровня:

классный

buildscript {
    repositories {
        google()
    }
    dependencies {
        def nav_version = "2.8.9"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }
}

Котлин

buildscript {
    repositories {
        google()
    }
    dependencies {
        val nav_version = "2.8.9"
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")
    }
}

Вам также необходимо применить один из двух доступных плагинов.

Чтобы сгенерировать код языка Java, подходящий для Java или смешанных модулей Java и Kotlin, добавьте эту строку в файл build.gradle вашего приложения или модуля :

классный

plugins {
  id 'androidx.navigation.safeargs'
}

Котлин

plugins {
    id("androidx.navigation.safeargs")
}

В качестве альтернативы, чтобы сгенерировать код Kotlin, подходящий для модулей только Kotlin, добавьте:

классный

plugins {
  id 'androidx.navigation.safeargs.kotlin'
}

Котлин

plugins {
    id("androidx.navigation.safeargs.kotlin")
}

У вас должно быть android.useAndroidX=true в файле gradle.properties в соответствии с переходом на AndroidX .

Информацию об использовании расширений Kotlin смотрите в документации ktx .

Дополнительные сведения о зависимостях см. в разделе Добавление зависимостей сборки .

Обратная связь

Ваши отзывы помогают сделать Jetpack лучше. Дайте нам знать, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете добавить свой голос к существующей проблеме, нажав кнопку со звездочкой.

Создать новую задачу

Дополнительную информацию см. в документации по системе отслеживания проблем .

Версия 2.9

Версия 2.9.0-альфа08

12 марта 2025 г.

Выпущен androidx.navigation:navigation-*:2.9.0-alpha08 . Версия 2.9.0-alpha08 содержит эти коммиты .

Исправления ошибок

  • Из навигации 2.8.9 : исправлена ​​регрессия, обнаруженная в навигации 2.8.8 , которая требовала, чтобы глубокая ссылка точно соответствовала всем полям запроса или намерения глубокой ссылки, чтобы считаться совпадением. Это привело к тому, что глубокие ссылки, которые содержали частичные совпадения полей и не позволяли другим, переставали работать. ( Ie5e36 , б/399826566 )

Внешний вклад

  • Новая общая функция синтаксического анализатора для создания NavUri . Спасибо Константин Цховребов! ( Если0а6а )

Версия 2.9.0-альфа07

26 февраля 2025 г.

Выпущен androidx.navigation:navigation-*:2.9.0-alpha07 . Версия 2.9.0-alpha07 содержит эти коммиты .

Исправления ошибок

  • Исправлена ​​проблема, из-за которой попытка saveState с неинклюзивным pop приводила к нулевому значению saveState, что могло привести к сбою при восстановлении. ( I9f3e8 , б/395091644 )
  • Из навигации 2.8.8 : исправлено сопоставление NavDeepLink , при котором глубокая ссылка и запрос на глубокую ссылку должны точно совпадать по uri, действию и mime. Сопоставление больше не допускается, если совпадают только одно или два поля. ( I3b029 , б/395712033 )
  • Из навигации 2.8.8 : исправлена ​​ошибка, из-за которой маршруты с подстановочными путями не совпадают с добавленной глубокой ссылкой ( I7ea92 , b/389970341 ).

Внешний вклад

  • Извлеките API общей навигации, среды выполнения навигации и API создания навигации на общую платформу. Спасибо Константин Цховребов! ( I1e626 , Ica76f , Idf479 )

Известные проблемы

  • Из-за работы над адресом b/395712033 глубокие ссылки неправильно должны иметь все те же поля, что и запрос диплинка и/или Intent . Глубокие ссылки должны соответствовать только имеющимся у них полям, а невключенные поля следует игнорировать. Это было исправлено в более позднем выпуске как часть b/399826566 .

Версия 2.9.0-альфа06

12 февраля 2025 г.

Выпущен androidx.navigation:navigation-*:2.9.0-alpha06 . Версия 2.9.0-alpha06 содержит эти коммиты .

Новые возможности

  • Действия Navigation Safe Args теперь генерируются с аннотацией @CheckResult , чтобы гарантировать их использование. ( I14d4c , б/356323084 )

Исправления ошибок

  • Исправлена ​​ошибка в NavController , из-за которой состояния backStack неправильно пытались восстановить в массив, когда они были сохранены в списке. ( Idfb9b )
  • Начиная с версии Navigation 2.8.7 : Navigation Safe Args теперь обеспечивает поддержку составных пунктов назначения. ( I35320 , б/362791955 )

Версия 2.9.0-альфа05

29 января 2025 г.

Выпущен androidx.navigation:navigation-*:2.9.0-alpha05 . Версия 2.9.0-alpha05 содержит эти коммиты .

Исправления ошибок

  • Исправлена ​​проблема, приводившая к неожиданному масштабированию анимации при использовании Navigation Compose. ( I480f4 , б/353294030 )
  • Из навигации 2.8.6 : метки NavDestination , предоставленные через XML, будут анализироваться через NavType.get , чтобы гарантировать соблюдение пользовательской логики NavType . ( I7ec2f , б/388100796 )
  • Из навигации 2.8.6 : при переходе к действию с помощью dataPattern ActivityNavigator теперь попытается закодировать значение arg с помощью NavType аргумента. ( I16376 , б/383616432 )
  • Из навигации 2.8.5 : исправлена ​​проблема, приводившая к неожиданному масштабированию анимации при использовании Navigation Compose и вызове навигации в том же кадре, где заканчивается текущая анимация. ( I26cb1 , б/353294030 )

Версия 2.9.0-альфа04

11 декабря 2024 г.

Выпущен androidx.navigation:navigation-*:2.9.0-alpha04 . Версия 2.9.0-alpha04 содержит эти коммиты .

Новые возможности

В таблице ниже представлены API-интерфейсы reified и KClass.

материализованный ККласс
composable<TestClass> { } composable(TestClass::class) { }
navigation<NestedGraph>(startDestination = TestClass::class) navigation(route = NestedGraph::class, startDestination = TestClass::class)
dialog<TestClass> {} dialog(TestClass::class) {}
navDeepLink<TestClass>(baseUri) navDeepLink(TestClass::class, baseUri)
NavDeepLink.Builder.setUriPattern<TestClass>(baseUri) NavDeepLink.Builder.setUriPattern(TestClass::class, baseUri)
NavDestinationBuilder.deepLink<TestDeepLink>(baseUri) { } NavDestinationBuilder.deepLink(TestDeepLink::class, baseUri) { }
navController.getBackStackEntry<TestClass>() navController.getBackStackEntry(TestClass::class)
navController.popBackStack<TestClass>(true) navController.popBackStack(TestClass::class, true)
navController.clearBackStack<TestClass>() navController.clearBackStack(TestClass::class)
NavOptions.setPopUpTo<TestClass>() NavOptions.setPopUpTo(TestClass::class)
navOptions { popUpTo<TestClass> {...} } navOptions { popUpTo(TestClass::class) {...} }
NavGraph.setStartDestination<TestClass>() NavGraph.setStartDestination(TestClass::class)
NavGraph.findNode<TestClass>() NavGraph.findNode(TestClass::class)
backStackEntry.toRoute<TestClass>() backStackEntry.toRoute(TestClass::class)
savedStateHandle.toRoute<TestClass>() savedStateHandle.toRoute(TestClass::class)

Изменения API

  • Перегрузка NavGraph.setStartDestination , специфичная для Kotlin, для обеспечения безопасности типов скрыта из исходных кодов Java. ( Ic640c , б/364634035 )

Исправления ошибок

  • Из навигации 2.8.5 : исправлена ​​проблема, из-за которой NavHost мог выдать исключение внутри PredictiveBackHandler , если задний стек выталкивается до 1 записи и в том же кадре запускается системный возврат. ( I1a429 , б/375343407 )
  • Из навигации 2.8.5 : исправлено исключение NavDestination NullPointerException при обновлении startDestination графика. ( I99421 , б/361560785 )

Внешний вклад

  • Из навигации 2.8.5 : безопасность типа навигации теперь поддерживает List<Enum> в качестве типа аргумента маршрута без необходимости использования какого-либо специального NavType . Спасибо Чаба Козак ! ( GH-725 , б/375559962 )

Версия 2.9.0-альфа03

13 ноября 2024 г.

Выпущен androidx.navigation:navigation-*:2.9.0-alpha03 . Версия 2.9.0-alpha03 содержит эти коммиты .

Новые возможности

  • Безопасность типа навигации теперь поддерживает классы значений в качестве маршрута или типа аргумента маршрута. ( I9344a , б/374347483 )

Исправления ошибок

  • Исправлено исключение ConcurrentModificationException , которое могло возникнуть, когда LifecycleObserver , прикрепленный к NavBackStackEntry инициирует изменение обратного стека, когда хост LifecycleOwner , такой как содержащее действие или фрагмент, меняет состояние своего жизненного цикла. ( Ia9494 )

Версия 2.9.0-альфа02

30 октября 2024 г.

Выпущен androidx.navigation:navigation-*:2.9.0-alpha02 . Версия 2.9.0-alpha02 содержит эти коммиты .

Внешний вклад

  • Новый общий метод NavController.handleDeepLink(request: NavDeepLinkRequest) . Спасибо Константин Цховребов! ( I3e228 )

Версия 2.9.0-альфа01

16 октября 2024 г.

Выпущен androidx.navigation:navigation-*:2.9.0-alpha01 . Версия 2.9.0-alpha01 содержит эти коммиты .

Новые возможности

  • Пользовательские навигаторы теперь могут помечать свои пункты назначения как реализацию интерфейса SupportingPane , который указывает NavController , что эти пункты назначения будут отображаться рядом с другими пунктами назначения. Используя этот интерфейс, например, можно RESUMED нескольких пунктов назначения одновременно. ( Ид5559 )
  • Из навигации 2.8.3 : добавлены новые проверки для модулей navigation-common , navigation-runtime и navigation-compose которые помогают идентифицировать любые типобезопасные маршруты, которые неправильно аннотированы с помощью @Serializable . Эта проверка применяется ко всем функциям расширения NavGraphBuilder и NavDeepLinkBuilder . ( I4a259 , I95402 , Ie601a , Id8c6e , I28bda , b/362725816 )
  • Из навигации 2.8.3 : добавлены новые проверки для модулей navigation-common , navigation-runtime и navigation-compose которые помогают идентифицировать любые типобезопасные маршруты с аргументами Enum, которые неправильно аннотированы @Keep . Эта проверка применяется ко всем функциям расширения NavGraphBuilder и NavDeepLinkBuilder . ( I4a259 , I95402 , Ie601a , Id8c6e , I2b46f , b/358687142 )

Изменения поведения

  • Попытка использовать NavController , который ранее был DESTROYED теперь вызовет исключение IllegalStateException . ( I520da , б/369616172 )

Исправления ошибок

  • Обновите исключение класса Enum не найдено, чтобы предложить использовать аннотацию @Keep в случае, если класс Enum будет удален в мини-сборках. ( I90e79 , б/358137294 )

Известные проблемы

  • Существует проблема с новыми правилами проверки, добавленными в Navigation 2.8.* , которая вызывает ошибку Obsolete custom lint check при попытке запустить проверку с помощью плагина Android Gradle 8.4+. ( б/368070326 , б/371463741 )

Версия 2.8

Версия 2.8.9

12 марта 2025 г.

Выпущен androidx.navigation:navigation-*:2.8.9 . Версия 2.8.9 содержит эти коммиты .

Исправления ошибок

  • Исправлена ​​регрессия, обнаруженная в навигации 2.8.8 , которая требовала, чтобы глубокая ссылка точно соответствовала всем полям запроса или намерения глубокой ссылки, чтобы считаться совпадением. Это привело к тому, что глубокие ссылки, которые содержали частичные совпадения полей и не позволяли другим, переставали работать. ( Ie5e36 , б/399826566 )

Версия 2.8.8

26 февраля 2025 г.

Выпущен androidx.navigation:navigation-*:2.8.8 . Версия 2.8.8 содержит эти коммиты .

Исправления ошибок

  • Исправлена ​​ошибка, из-за которой маршруты с подстановочными путями не соответствовали добавленной глубокой ссылке. ( I7ea92 , б/389970341 )
  • Исправлено сопоставление NavDeepLink , при котором глубокая ссылка и запрос на глубокую ссылку должны точно совпадать по uri, действию и mime. Сопоставление больше не допускается, если совпадают только одно или два поля. ( I3227f , б / 395712033 )

Известные проблемы

  • Из-за работы над адресом b/395712033 глубокие ссылки неправильно должны иметь все те же поля, что и запрос диплинка и/или Intent . Глубокие ссылки должны соответствовать только имеющимся у них полям, а невключенные поля следует игнорировать. Это было исправлено в более позднем выпуске как часть b/399826566 .

Версия 2.8.7

12 февраля 2025 г.

Выпущен androidx.navigation:navigation-*:2.8.7 . Версия 2.8.7 содержит эти коммиты .

Исправления ошибок

  • Navigation Safe Args теперь обеспечивает поддержку составных пунктов назначения. ( I35320 , б/362791955 )

Версия 2.8.6

29 января 2025 г.

Выпущен androidx.navigation:navigation-*:2.8.6 . Версия 2.8.6 содержит эти коммиты .

Исправления ошибок

  • Метки NavDestination , предоставленные через XML, будут анализироваться через NavType.get , чтобы гарантировать соблюдение пользовательской логики NavType . ( Id366d , б/388100796 )
  • При переходе к действию с помощью dataPattern ActivityNavigator теперь попытается закодировать значение arg с помощью NavType аргумента. ( I1a71d , б/383616432 )

Версия 2.8.5

11 декабря 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.5 . Версия 2.8.5 содержит эти коммиты .

Исправления ошибок

  • Исправлена ​​проблема, из-за которой NavHost мог выдать исключение внутри PredictiveBackHandler , если задний стек выталкивается до 1 записи и в том же кадре запускается системный возврат. ( I1a429 , б/375343407 )
  • Исправлено исключение NavDestination NullPointerException при обновлении startDestination графа. ( I99421 , б/361560785 )
  • Исправлена ​​проблема, приводившая к неожиданному масштабированию анимации при использовании Navigation Compose и вызове навигации в том же кадре, где заканчивается текущая анимация. ( I26cb1 , б/353294030 )
  • Исправлено исключение ConcurrentModificationException , которое могло возникнуть, когда LifecycleObserver , прикрепленный к NavBackStackEntry инициирует изменение обратного стека, когда хост LifecycleOwner , такой как содержащее действие или фрагмент, меняет состояние своего жизненного цикла. ( Ia9494 )

Внешний вклад

  • Безопасность типа навигации теперь поддерживает List<Enum> в качестве типа аргумента маршрута без необходимости использования какого-либо специального NavType . Спасибо Чаба Козак ! ( GH-725 , б/375559962 )

Версия 2.8.4

13 ноября 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.4 . Версия 2.8.4 содержит эти коммиты .

Новые возможности

  • Из навигации 2.9.0-alpha03 : безопасность типа навигации теперь поддерживает класс значения как маршрут или как тип аргумента маршрута ( I9344a , b/374347483 ).

Исправления ошибок

  • Из навигации 2.9.0-alpha01 : попытка использовать NavController , который ранее был DESTROYED теперь будет вызывать исключение IllegalStateException . ( I520da , б/369616172 )

Версия 2.8.3

16 октября 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.3 . Версия 2.8.3 содержит эти коммиты .

Новые возможности

  • Добавлены новые проверки lint для модулей navigation-common , navigation-runtime и navigation-compose которые помогают идентифицировать любые типобезопасные маршруты, которые неправильно аннотированы с помощью @Serializable . Эта проверка применяется ко всем функциям расширения NavGraphBuilder и NavDeepLinkBuilder . ( I4a259 , I95402 , Ie601a , Id8c6e , I28bda , b/362725816 )
  • Добавлены новые проверки lint для модулей navigation-common , navigation-runtime и navigation-compose которые помогают идентифицировать любые типобезопасные маршруты с аргументами Enum, которые неправильно аннотированы @Keep . Эта проверка применяется ко всем функциям расширения NavGraphBuilder и NavDeepLinkBuilder . ( I4a259 , I95402 , Ie601a , Id8c6e , I2b46f , b/358687142 )

Исправления ошибок

  • Исправлена ​​проблема, из-за которой новые правила проверки, добавленные в Navigation 2.8.* , вызывали ошибку Obsolete custom lint check при попытке запустить проверку с помощью плагина Android Gradle 8.4+. ( I1be3d , б/368070326 , б/371463741 )

Известные проблемы

  • Навигационный lint выдаст ошибку проверки устаревшего пользовательского lint при попытке запустить lint с помощью Lint 16 (AGP 8.7) или выше. ( б/371926651 )

Версия 2.8.2

2 октября 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.2 . Версия 2.8.2 содержит эти коммиты .

Новые возможности

  • Безопасность типов навигации теперь поддерживает сериализуемые классы, которые включают Double , Double? , DoubleArray , DoubleArray? , List<Double> и List<Double>? без необходимости использования какого-либо специального NavType . ( I570eb , Ibc4c0 , I37461 , I5bed4 , b/359245753 )

Исправления ошибок

  • Улучшено сообщение об ошибке: когда навигации не удается сопоставить аргумент маршрута с NavType , новое сообщение об ошибке будет содержать имя аргумента, полное имя аргумента и полное имя маршрута. ( Id8416 , б/346264232 )

Версия 2.8.1

18 сентября 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.1 . Версия 2.8.1 содержит эти коммиты .

Новые возможности

  • Добавлено новое правило проверки, гарантирующее использование функции popBackStack , которая принимает конкретный тип класса при попытке popBackStack с использованием типобезопасных API. ( Ief161 , б/358095343 )

Исправления ошибок

  • Для навигации теперь требуется, чтобы маршрут, передаваемый в startDestination NavGraph , содержал значения для всех обязательных аргументов, включая аргументы, которые не допускают значения NULL и не имеют значения по умолчанию. ( I18e74 , б/362594265 )
  • В аргументах навигационной безопасности добавлена ​​поддержка строк, не допускающих значения NULL, так что значения «null» будут анализироваться и сохраняться в пакете как есть. Это отличается от существующего поведения, при котором «нулевые» значения анализируются в нулевой объект. Это изменение применимо только к строковым типам, не допускающим значения NULL. Строки, допускающие значение NULL, остаются неизменными. ( I08b4a , б/348936238 )
  • NavDestination больше не может иметь глубокую ссылку, кроме как через глубокую ссылку, которая была явно добавлена ​​к месту назначения. Это также означает, что вы можете перейти к маршруту пункта назначения только с помощью перегруженной функции навигации, которая принимает строковый маршрут. Это устраняет уязвимость, которая позволяла создать глубокую ссылку на потенциально защищенный пункт назначения. ( Ie30e6 )

Обновление зависимостей

  • Navigation Safe Args теперь зависит от Kotlin 1.9.24, а не от Kotlin 2.X, что гарантирует, что разработчикам не придется обновляться. ( а4129а )
  • Навигация Compose теперь зависит от Compose 1.7.2 .

Версия 2.8.0

4 сентября 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0 . Версия 2.8.0 содержит эти коммиты .

Важные изменения с версии 2.7.0

Навигация: Типовая безопасность Kotlin DSL

  • Навигация теперь обеспечивает типобезопасность для Kotlin DSL (используемого Navigation Compose) с использованием сериализации Kotlin, что позволяет вам определять пункты назначения в навигационном графе с помощью типобезопасных объектов и классов данных:
    // Define a home destination that doesn't take any arguments
    @Serializable
    object Home

    // Define a profile destination that takes an ID
    @Serializable
    data class Profile(val id: String)

    // Now define your NavHost using type safe objects
    NavHost(navController, startDestination = Home) {
        composable<Home> {
            HomeScreen(onNavigateToProfile = { id ->
                navController.navigate(Profile(id))
            })
        }
        composable<Profile> { backStackEntry ->
            val profile: Profile = backStackEntry.toRoute()
            ProfileScreen(profile)
        }
    }

Дополнительную информацию см. в блоге «Навигация по компоновке и безопасности типов» .

Навигация. Составление прогноза. Назад.

  • Navigation Compose теперь обеспечивает поддержку Predictive внутри приложения через новые API-интерфейсы SeekableTransitionState из compose-animation. Это позволяет вам использовать жест назад, чтобы увидеть предыдущий пункт назначения с вашим пользовательским переходом, прежде чем принять решение либо подтвердить транзакцию с помощью завершенного жеста, либо отменить ее.

Составной фрагмент навигации

  • Добавлен новый артефакт navigation-fragment-compose , который включает альтернативу NavHostFragment ComposableNavHostFragment , которая позволяет добавлять составные пункты назначения в XML-файлы навигации. Каждое composable назначение должно быть выражено как метод @Composable верхнего уровня без аргументов, полное имя которого используется в качестве атрибута android:name в каждом пункте назначения. При переходе к одному из этих пунктов назначения создается содержащий фрагмент для отображения составного содержимого.
  // In HomeScreen.kt
  @Composable
  fun HomeScreen() {
    // Your Composable content here
  }

  // In your navigation.xml
  <composable
    android:id="@+id/home_screen"
    android:name="com.example.HomeScreenKt\$HomeScreen" />

Другие изменения

  • Навигация Compose теперь зависит от Compose 1.7.0.
  • Навигация теперь предоставляет новый класс CollectionNavType<T> , подкласс NavType<T> для аргументов на основе коллекций, таких как списки, массивы, карты. Все массивы NavType по умолчанию ( IntArrayType , LongArrayType , FloatArrayType , BoolArrayType и StringArrayType ) теперь наследуются от этого нового класса.
  • NavType теперь имеет встроенную поддержку списков Int, String, Boolean, Float и Long.

Версия 2.8.0-rc01

21 августа 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-rc01 . Версия 2.8.0-rc01 содержит эти коммиты .

Исправления ошибок

  • Исправлен сбой навигации при передаче классов Enum верхнего уровня в качестве типобезопасных аргументов. ( I0ba76 , б/358137294 )
  • Навигация 2.8 теперь корректно работает с SDK 34 и не будет переключаться на SDK 35 до выхода версии 2.9 вместе с остальными библиотеками AndroidX. ( б/358798728 )

Версия 2.8.0-бета07

7 августа 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-beta07 . Версия 2.8.0-beta07 содержит эти коммиты .

Известные проблемы

  • Из-за b/358137294 по умолчанию поддерживаются только Enums, вложенные в другой класс. Перечисления верхнего уровня будут поддерживаться в следующем выпуске.

Исправления ошибок

  • При навигации к повторяющимся или общим пунктам назначения приоритет отдается переходу к ближайшему совпадающему пункту назначения из текущего местоположения на графике. ( Ic89a4 , б/352006850 )
  • Для навигации по безопасным аргументам теперь добавлен новый NavType.EnumType . Это означает, что типы Enum больше не требуют пользовательских NavType . Обратите внимание, что SerialName Enum должно быть полным именем по умолчанию. ( I66d22 , б/346475493 )
  • В навигацию по безопасным аргументам добавлена ​​встроенная поддержка типов аргументов, допускающих значение NULL, включая Int? , Long? , Float? , Boolean? и Enum<*>? . ( I32d13 , I1c580 , Ifba66 , I978b0 , Ide076 , b/351994237 )
  • startDestination NavGraph теперь будет использовать значения аргументов по умолчанию, если маршрут startDestination , переданный в NavGraph , в точности равен startDestination.route . ( I13762 , б/354046047 )

Версия 2.8.0-бета06

24 июля 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-beta06 . Версия 2.8.0-beta06 содержит эти коммиты .

Исправления ошибок

  • Исправлена ​​проблема, из-за которой проверки WrongStartDestinationType не проверяли объекты Companion в переданном типе класса, из-за чего lint не мог обнаружить ошибку. ( I92b09 )

Версия 2.8.0-бета05

10 июля 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-beta05 . Версия 2.8.0-beta05 содержит эти коммиты .

Исправления ошибок

  • Исправлен сбой навигации singleTop , когда вложенные NavGraphs используют один и тот же маршрут startDestination . ( I17b94 , б/294408596 )

Версия 2.8.0-бета04

26 июня 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-beta04 . Версия 2.8.0-beta04 содержит эти коммиты .

Исправления ошибок

  • Навигация теперь поддерживает навигацию с пустыми строками в аргументах пути. ( Ic5dbd , б/339481310 )
  • Улучшите сообщение об ошибке для пользовательских сериализаторов, объявленных непосредственно в полях класса через @Serializable(with =...) чтобы уточнить, что в настоящее время эта функция не поддерживается. ( I052b0 , б/341319151 )
  • API-интерфейс теста SavedStateHandleFactory теперь можно использовать в тестах, отличных от Android, но для поддержки анализа аргументов с помощью Bundles потребуется Robolectric. ( I76cdc , б/340966212 )
  • Исправлен сбой при восстановлении состояния при возобновлении работы приложения после смерти процесса с использованием типобезопасной навигации в Compose. ( Ia8f38 , б/341801005 )
  • Исправлена ​​проблема в Navigation Compose, из-за которой после отмены прогнозируемого жеста возврата элемент NavBackStackEntry , к которому возвращается пользователь, никогда не возвращается в состояние RESUMED жизненного цикла. Это также гарантирует, что возвращающийся пункт назначения правильно анимируется, а не фиксируется на месте после броска. ( I97a0c , б/346608857 )
  • При использовании функции Predictive Back с функцией Navigation Compose отображаемый пункт назначения теперь будет иметь правильный z-порядок и правильно анимироваться поверх входящего пункта назначения. ( I2077b , б/345993681 )

Версия 2.8.0-бета03

12 июня 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-beta03 . Версия 2.8.0-beta03 содержит эти коммиты .

Изменения API

  • CollectionNavType имеет новый абстрактный метод emptyCollection() . Переопределите это, чтобы обрабатывать пустую коллекцию, переданную в качестве аргумента. ( Ie4d84 , б/341723133 )

Исправления ошибок

  • Добавлена ​​документация по NavType.serializeAsValue и serializeAsValues , чтобы подчеркнуть, что окончательные выходные данные должны быть закодированы Uri. ( Ида6бд , б/344943214 )
  • Исправлен сбой при вызове toRoute<T> с нулевым аргументом CollectionNavType . При навигации с нулевым значением CollectionNavType выходным аргументом будет значение по умолчанию, объявленное в вашем классе Serializable, или возвращаемое значение emptyCollection() если значение по умолчанию отсутствует. ( I84158 , Id630f , б/342672856 )

Версия 2.8.0-бета02

29 мая 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-beta02 . Версия 2.8.0-beta02 содержит эти коммиты .

Исправления ошибок

  • Исправлен сбой ClassCastException при использовании NavBackStackEntry.toRoute с пользовательским NavType , допускающим значение NULL. ( I1c29b , б/342239473 )
  • Исправлены проблемы с восстановлением состояния обратного стека навигации, возникающие при попытке восстановить запись обратного стека, которая недоступна по идентификатору из текущего пункта назначения. Поскольку маршруты поддерживаются идентификаторами, это также затронуло пункты назначения, построенные с использованием маршрутов. Это также устраняет сбой, вызванный вызовом clearBackStack() , который имел ту же основную проблему. ( I423c3 , б/339908057 )

Версия 2.8.0-бета01

14 мая 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-beta01 . Версия 2.8.0-beta01 содержит эти коммиты .

Изменения API

  • SavedStateHandle.toRoute() теперь принимает параметр typeMap для пользовательских типов аргументов. ( Ie39fb , б/339026523 )
  • В navigation-testing добавлен тестовый API для создания SavedStateHandle из сериализуемого объекта Kotlin. ( Id4867 , б/339080702 )

Исправления ошибок

  • Добавлены недостающие документы по параметрам для функций Navigation Kotlin DSL. ( I26a36 )

Версия 2.8.0-альфа08

1 мая 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-alpha08 . Версия 2.8.0-alpha08 содержит эти коммиты .

Безопасные аргументы в навигации

Эта функция использует сериализацию Kotlin, чтобы вы могли определять пункты назначения в графе навигации с помощью типобезопасных объектов и классов данных:

  // Define a home destination that doesn't take any arguments
  @Serializable
  object Home

  // Define a profile destination that takes an ID
  @Serializable
  data class Profile(val id: String)

  // Now define your NavHost using type safe objects
  NavHost(navController, startDestination = Home) {
      composable<Home> {
          HomeScreen(onNavigateToProfile = { id ->
              navController.navigate(Profile(id))
          })
      }
      composable<Profile> { backStackEntry ->
          val profile: Profile = backStackEntry.toRoute()
          ProfileScreen(profile)
      }
  }

Дополнительную информацию см. в блоге «Навигация по компоновке и безопасности типов» .

Новые возможности

  • Артефакт navigation-fragment-compose теперь предоставляет композицию LocalFragment , локальную для составных методов внутри ComposableFragment . ( Если35e5 )
  • NavType теперь имеет встроенную поддержку списков Int, String, Boolean, Float и Long. ( I4b6dd , Ia914c , b/188693139 )

Версия 2.8.0-альфа07

17 апреля 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-alpha07 . Версия 2.8.0-alpha07 содержит эти коммиты .

Новые возможности

  • Добавляет новый артефакт navigation-fragment-compose , который включает альтернативу NavHostFragment ComposableNavHostFragment , которая позволяет добавлять composable пункты назначения в XML-файлы навигации. Каждое composable назначение должно быть выражено как метод @Composable верхнего уровня без аргументов, полное имя которого используется в качестве атрибута android:name в каждом пункте назначения. При переходе к одному из этих пунктов назначения создается содержащий фрагмент для отображения составного содержимого. ( I0ef2e , б/265480755 )

    // In HomeScreen.kt
    @Composable
    fun HomeScreen() {
      // Your Composable content here
    }
    
    // In your navigation.xml
    <composable
      android:id="@+id/home_screen"
      android:name="com.example.HomeScreenKt\$HomeScreen" />
    

Изменения API

  • Продолжалась поддержка Safe Args в Navigation Compose с использованием подхода, основанного на сериализации Kotlin. Эти API еще не завершены и отмечены аннотацией ExperimentalSafeArgsApi . Эта аннотация будет удалена, когда вся поверхность API будет завершена в будущем выпуске. ( Iefd95 , I409c8 , I5b5ac , I7e753 , I960f8 , I3eabd , I8ed5a , Ied2c9 , I9b73c , I554db , Ib3aba , Ia668d , b/188693139 )

Версия 2.8.0-альфа06

3 апреля 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-alpha06 . Версия 2.8.0-alpha06 содержит эти коммиты .

Изменения API

Исправления ошибок

  • NavHost теперь использовал Alignment.TopStart в качестве аргумента contentAlignment по умолчанию. Это приводит его в соответствие со значением по умолчанию для AnimatedContent и исправляет некоторые случаи неожиданного масштабирования при переходе по центру. ( I09e72 , б/330111602 )
  • При нажатии интеллектуального жеста назад во время использования Navigation Compose NavHost теперь правильно завершает пользовательский переход, а не немедленно завершает его. ( I99017 , б/327292110 )

Версия 2.8.0-альфа05

20 марта 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-alpha05 . Версия 2.8.0-alpha05 содержит эти коммиты .

Новые возможности

  • Теперь вы можете передавать аргументы в startDestination NavGraph непосредственно в маршруте startDestination , не полагаясь на defaultValue . Это также относится и к вложенным startDestinations NavGraph . ( I0e0b5 , б/109505019 , б/188693139 )

Изменения API

  • Добавлен новый абстрактный класс CollectionNavType<T> , подкласс NavType<T> для аргументов на основе коллекций, таких как списки, массивы, карты. ( Ic6d63 , б/188693139 )
  • Все массивы NavType по умолчанию ( IntArrayType , LongArrayType , FloatArrayType , BoolArrayType и StringArrayType ) теперь относятся к типу CollectionNavType ( Idcf79 , b/188693139 ).
  • NavType теперь предоставляет новый открытый API valueEquals , который определяет, равны ли два значения одного типа друг другу. ( I6cb97 , б/327229511 )

Исправления ошибок

  • Параметры запроса в глубоких ссылках теперь допускают значения в форме фигурных скобок вокруг имени аргумента (т. е. {argName} ) в качестве допустимых значений для строковых NavTypes . Это устраняет проблему, из-за которой такое значение считалось недействительным (или отсутствовало значение) для всех типов. ( I18302 , б/327274038 )
  • Функции NavController , поддерживающие такие маршруты, как navigate или popBackStack , теперь могут правильно сопоставлять маршруты, заполненные аргументами Array NavTypes . ( Iea805 , б/327229511 )

Версия 2.8.0-альфа04

6 марта 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-alpha04 . Версия 2.8.0-alpha04 содержит эти коммиты .

Новые возможности

  • Теперь вы можете указать SizeTranform для своих переходов в Navigation Compose, определив их как часть инициализации composable и/или navigation функций. ( I91062 , б / 296912651 )

Исправления ошибок

  • Исправлена ​​проблема, из-за которой NavHost в функции «Создать навигацию» не отображал должным образом переход при использовании «Назад к системе» без жестов. ( Iceeae , б/325998468 )

Версия 2.8.0-альфа03

21 февраля 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-alpha03 . Версия 2.8.0-alpha03 содержит эти коммиты.

Изменения API

  • NavBackStackEntry.savedStateHandle теперь помечен как @MainThread , поскольку он в любом случае использует код, который в любом случае должен находиться в основном потоке. ( Ibb988 , б/299523245 )

Исправления ошибок

  • Исправлена ​​проблема в навигации, из-за которой модели представления NavGraph были DESTROYED слишком рано, поскольку ViewModel связанной записи не была частью сохраненного состояния. ( Ib6bb7 , б/317581849 )

Обновление зависимостей

Версия 2.8.0-альфа02

7 февраля 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-alpha02 . Версия 2.8.0-alpha02 содержит эти коммиты.

Новые возможности

  • Navigation Compose теперь обеспечивает поддержку Predictive в приложении через новые API-интерфейсы SeekableTransitionState из compose-animation. Это позволяет вам использовать жест назад, чтобы увидеть предыдущий пункт назначения с вашим пользовательским переходом, прежде чем принять решение либо подтвердить транзакцию с помощью завершенного жеста, либо отменить ее. ( I8b8e9 )

Версия 2.8.0-альфа01

24 января 2024 г.

Выпущен androidx.navigation:navigation-*:2.8.0-alpha01 . Версия 2.8.0-alpha01 содержит эти коммиты.

Исправления ошибок

  • Исправлена ​​утечка BackStackState , из-за которой несколько вызовов saveState в пункте назначения приводили к сохранению нескольких состояний, но восстановить можно было только первое. ( I598b0 , б/309559751 )
  • Исправлена ​​проблема, из-за которой аргументы, отличные от String, не отображались должным образом при использовании помощников NavigationUI для заполнения заголовков панелей приложений. ( #636 , б/316676794 )

Обновление зависимостей

  • Навигация Compose теперь зависит от Compose 1.7.0-alpha01 исправляющего проблему, которая могла привести к неожиданному масштабированию анимации. ( б/297258205 )

Внешний вклад

  • Спасибо SimonMarquis за исправление проблемы с отображением нестроковых аргументов при использовании помощников NavigationUI для заполнения заголовков панелей приложений.

Версия 2.7.7

Версия 2.7.7

7 февраля 2024 г.

Выпущен androidx.navigation:navigation-*:2.7.7 . Версия 2.7.7 содержит эти коммиты.

Исправления ошибок

  • Перенесено из навигации 2.8.0-alpha01 : исправлена ​​утечка BackStackState , из-за которой несколько вызовов saveState() для одного NavBackStackEntry приводили к сохранению нескольких состояний, но восстановить можно было только первое сохраненное состояние. ( I598b0 , б/309559751 )
  • Перенесено из навигации 2.8.0-alpha01 : исправлена ​​проблема, из-за которой нестроковые аргументы не отображались должным образом при использовании помощников NavigationUI для заполнения заголовков панелей приложений. ( #636 , б/316676794 )

Внешний вклад

  • Спасибо SimonMarquis за исправление проблемы с отображением нестроковых аргументов при использовании помощников NavigationUI для заполнения заголовков панелей приложений.

Версия 2.7.6

Версия 2.7.6

13 декабря 2023 г.

Выпущен androidx.navigation:navigation-*:2.7.6 . Версия 2.7.6 содержит эти коммиты.

Исправления ошибок

  • Функция NavGraph equals() теперь корректно учитывает узлы другого графа, а не только вызывающего. Это гарантирует, что графы с узлами с разными идентификаторами больше не будут считаться равными ( I401cb , b/311414915 ).

Версия 2.7.5

Версия 2.7.5

1 ноября 2023 г.

Выпущен androidx.navigation:navigation-*:2.7.5 . Версия 2.7.5 содержит эти коммиты.

Улучшения производительности

  • Значительно улучшена производительность (как по времени, так и по количеству выделений) при сравнении двух графиков. Это означает, что такие вызовы, как setGraph , которые внутренне сравнивают новый граф с существующим, выполняются намного быстрее и приводят к меньшему количеству пропущенных кадров. Спасибо Михалу З за тщательный анализ, который привел к этому улучшению. ( I6ad62 )
  • NavHost теперь будет отображать начальный пункт назначения на первом проходе композиции вместо того, чтобы ждать второго прохода для чтения обновленного состояния. ( I439a7 , б/304852206 )

Исправления ошибок

  • Исправлена ​​проблема, из-за которой ваш задний стек выскакивал, если вы вызывали setGraph более одного раза с одним и тем же графом, только если в вашем графике был пункт назначения, содержащий действие, связывающее два пункта назначения. ( Ieaed7 )
  • Диалоги, к которым быстро переходили и закрывали, больше не будут просачиваться в список NavController.visibleEntries . ( I67586 , б / 287969970 )
  • Когда запись извлекается с последующим изменением конфигурации, ViewModel записи теперь будет очищаться правильно, если saveState имеет значение false. ( Idf242 , б/298164648 )
  • Исправлена ​​проблема, из-за которой NavController мог обрабатывать одну и ту же глубокую ссылку более одного раза, если задний стек был полностью пуст до изменения конфигурации или вызова setGraph , только когда для входящего намерения был установлен флаг FLAG_ACTIVITY_NEW_TASK . ( I73c7f )

Обновления зависимостей

  • Навигация с помощью фрагментов теперь зависит от Fragment 1.6.2 , что устраняет проблему, из-за которой экземпляры ViewModel вложенных фрагментов не очищались при clearBackStack .

Версия 2.7.4

Версия 2.7.4

4 октября 2023 г.

Выпущен androidx.navigation:navigation-*:2.7.4 . Версия 2.7.4 содержит эти коммиты.

Новые возможности

  • Добавлена ​​поддержка popUpTo для использования маршрутов с аргументами, позволяющих вернуться к определенной записи, которая использует именно эти аргументы, что соответствует поддержке, найденной в popBackStack . ( I731f4 , б / 299255572 )

Исправления ошибок

  • Исправлена ​​проблема, из-за которой прерывание навигации с помощью другой навигации с помощью popUpTo приводило к сбою FragmentNavigator . ( I3c848 , б/301887045 )
  • Исправлена ​​проблема, из-за которой нажатие системы назад приводило к неправильному обновлению currentDestination в соответствии с отображаемым фрагментом. ( Id0d6c , б/289877514 )
  • Жизненный цикл DialogFragment теперь корректно переходит в состояние RESUMED , когда диалоговое окно над ним закрывается. ( I88f0d , б/301811387 )

Версия 2.7.3

Версия 2.7.3

20 сентября 2023 г.

Выпущен androidx.navigation:navigation-*:2.7.3 . Версия 2.7.3 содержит эти коммиты.

Исправления ошибок

  • Исправлена ​​проблема в навигации с фрагментами, которые привели к тому, что список visibleEntries содержат неправильные записи. ( I5caa9 , b/288520638 )
  • Исправлена ​​проблема, из -за которой место для плавающего окна (т.е. Dialogs , Bottomsheets и т. Д.) Никогда не получили RESUMED обратный вызов жизненного цикла. ( I3b866 , b/287505132 )

Версия 2.7.2

Версия 2.7.2

6 сентября 2023 года

androidx.navigation:navigation-*:2.7.2 выпущена. Версия 2.7.2 содержит эти коммиты.

Исправления ошибок

  • Навигация в настоящее время зависит от жизненного цикла 2.6.2 , исправляя взаимодействие между rememberSaveable и навигационным навигационным NavHost , которое вызвало бы rememberSaveable о состоянии назначения и любых экземпляров ViewModel , принадлежащих SavedStateHandle от правильного восстановления после смерти процесса и развлечения. ( B/298059596 , B/289436035 )
  • Исправлена ​​проблема при отображении нескольких диалогов в навигации, составленной одновременно, где частично скрытые диалоги (например, не самый верхний диалог) будут в CREATED состоянии жизненного цикла, а не в STARTED состоянии. ( AOSP/2728520 , B/289257213 )
  • Исправлена ​​проблема, показывая несколько диалогов в навигации, составляя одновременно, когда увольнение самого верхнего диалога приведет к застенчивому в STARTED жизненном цикле, а не RESUMED . ( AOSP/2629401 , B/286371387 )
  • Safe Args навигации больше не создает с нетерпением, если она на самом деле не выполняется. ( I0E385 , B/260322841 )

Обновление зависимости

  • Навигационная композиция теперь зависит от составления 1.5.1.

Версия 2.7.1

Версия 2.7.1

23 августа 2023 г.

androidx.navigation:navigation-*:2.7.1 выпускается. Версия 2.7.1 содержит эти коммиты.

Исправления ошибок

  • Исправлена ​​проблемы в навигации с композицией, где при использовании Scaffold можно было получить ошибку для попытки получить доступ к Lifecycle.State.DESTROYED State.destroyed ViewModel . ( I1dc11 , b/268422136 )

Версия 2.7.0

Версия 2.7.0

9 августа 2023 г.

androidx.navigation:navigation-*:2.7.0 выпускается. Версия 2.7.0 содержит эти коммиты.

Важные изменения с 2,6,0

Анимации от аккомпаниата

Теперь, когда AnimatedContent стабилен, мы смогли перенести код из анимации навигации в сопровождении обратно в навигацию.

Это означает, что вся поддержка для установки пользовательских переходов, которые существовали в AnimatedNavHost , напрямую поддерживается в NavHost .

Не будет внесено никаких дополнительных изменений в сопровождении анимации навигации, и мы в ближайшее время формируем ее, наряду с руководством о том, как перейти обратно в навигацию, но это будет обратным руководством по миграции без других изменений API, если вы уже используете новейший аккомпаунный альфа ( 0.31.2-alpha ). ( B/197140101 )

Исправления ошибок

  • Navhost в навигации теперь правильно перехватывает системные вызовы даже после того, как деятельность была остановлена ​​и возобновлена. ( ICB6DE , B/2791184447 )

Обновления зависимости

  • Навигация теперь зависит от составления 1.5.0 вверх по сравнению с 1.1.0 .

Версия 2.7.0-RC01

26 июля 2023 г.

androidx.navigation:navigation-*:2.7.0-rc01 выпускается. Версия 2.7.0-RC01 содержит эти коммиты.

Исправления ошибок

  • Исправлена ​​проблема, в которой EnterTransition и ExitTransition лямбдас, созданные как часть NavHost , потенциально могут оставаться в памяти даже после того, как NavHost будет удален из композиции. ( I893d0 )

Известные проблемы

  • Существует проблема из навигации 2.6.x, что при навигации с Popupto можно вызвать IllegalArgumentException . Возможно, что этого исключения можно избежать путем реструктуризации вашего графика, аналогично советам, предложенным здесь . ( B/287133013 )

Версия 2.7.0-beta02

28 июня 2023 г.

androidx.navigation:navigation-*:2.7.0-beta02 выпускается. Версия 2.7.0-beta02 содержит эти коммиты.

Исправления ошибок

  • Navigation Compose теперь имеет правильный Z-order для пользовательских переходов, которые используют навигацию с опцией popUpTo . ( /IB1C3A , B /285153947 )

Версия 2.7.0-beta01

7 июня 2023 г.

androidx.navigation:navigation-*:2.7.0-beta01 выпускается. Версия 2.7.0-beta01 содержит эти коммиты.

Исправления ошибок

  • NavHost в навигации теперь правильно перехватывает системные вызовы даже после того, как Activity была STOPPED ​​и RESUMED . ( ICB6DE , B/2791184447 )

Версия 2.7.0-Alpha01

24 мая 2023 г.

androidx.navigation:navigation-*:2.7.0-alpha01 выпускается. Версия 2.7.0-Alpha01 содержит эти коммиты.

Анимации от аккомпаниата

Теперь, когда AnimatedContent стабилен, мы смогли перенести код из анимации навигации в сопровождении обратно в навигацию.

Это означает, что вся поддержка для установки пользовательских переходов, которые существовали в AnimatedNavHost , напрямую поддерживается в NavHost .

Не будет внесено никаких дополнительных изменений в сопровождении анимации навигации, и мы в ближайшее время формируем ее, наряду с руководством о том, как перейти обратно в навигацию, но это будет обратным руководством по миграции без других изменений API, если вы уже используете новейший аккомпаунный альфа ( 0.31.2-alpha ). ( B/197140101 )

Исправления ошибок

  • Из навигации 2.6.0-rc02 : Исправлена ​​проблема с навигацией в фрагментах, где навигация с popUpTo и выталкивание фрагмента из заднего стека без воссоздания его представления приведет к тому, что система остановит работу. ( IEB8D4 , B/281726455 )

Обновления зависимости

  • Навигация теперь зависит от Compose 1.5.0-beta01 .

Версия 2.6.0

Версия 2.6.0

7 июня 2023 г.

androidx.navigation:navigation-*:2.6.0 выпускается. Версия 2.6.0 содержит эти коммиты.

Важные изменения в навигации с 2.5.0

  • arguments NavBackStackEntry и arguments , переданные в OnDestinationChangedListener теперь являются лишь копией неизменных аргументов, которые были созданы, когда вы перемещались в пункт назначения. Это означает, что любые изменения, внесенные в эти пучки, не будут отражены в последующих доступах к arguments или другим экземплярам OnDestinationChangedListener .
  • NavDeepLink теперь поддерживает значения по умолчанию для массивов, что позволяет поддержать повторные параметры запроса, которые будут отображаться в типе массива аргумента. NavType также теперь включает метод по умолчанию, который можно переопределить, чтобы объединить два проанализированных значения.
  • Пользовательские подклассы NavType теперь могут переопределять serializeAsValue , чтобы сериализовать значение в строку, позволяя как сериализацию, так и десериализацию (через parseValue ) полностью инкапсулировать в класс NavType . StringType теперь переопределяет этот метод, чтобы вызвать Uri.encode на данной String .

Важные изменения в навигационном составе с 2.5.0

  • При предварительном просмотре композиции с NavHost теперь он будет показывать startDestination NavGraph по умолчанию.
  • NavController.popBackStack(route) , NavController.getBackStackEntry(route) NavController.clearBackStack(route)
  • Попытка создать пустой NavDeepLink с использованием DSL navDeepLink Kotlin, теперь приведет к тому, что предупреждение о ворсе, указывающее на то, что глубокая ссылка нуждается в URI, действие и/или миметипе, чтобы быть действительным.

Важные изменения в навигации с фрагментами с 2.5.0

  • NavHostFragment больше не перехватывает саму кнопку «Система». Это позволяет базовому FragmentManager манага обрабатывать систему обратно. Это позволяет фрагменту 1.7.0-alpha01 и выше обеспечивать анимацию в приложении на устройствах Android U.
  • При использовании навигации с фрагментами попытка вручную выполнить транзакцию FragmentTransaction , которое добавляет фрагмент в задний стек FragmentManager , теперь бросит IllegalArgumentException . Вы всегда должны добавлять фрагменты через API navigate() .
  • При использовании точной строки ${applicationId} в качестве заполнителя в app:data и app:dataPattern в элементе деятельности файла навигации XML -файла, заполнитель будет автоматически заполнен с помощью packageName контекста при инфляции.
  • FragmentNavigator теперь использует API -интерфейсы перехода при навигации и выпчаве NavBackStackEntries . Это означает, что Lifecycle NavBackStackEntry теперь будет ждать, пока вступление и выйдет на фрагментные спецэффекты, прежде чем перемещать свой последний Lifecycle.State .
  • DialogFragmentNavigator теперь использует API -интерфейсы перехода при навигации и всплеске NavBackStackEntries . Это означает, что Lifecycle NavBackStackEntry теперь будет ждать, пока Lifecycle DialogFragment перейти к DESTROYED , прежде чем перейти к DESTROYED .
  • NavHostFragment теперь позволяет вам получить NavController , как только NavHostFragment прикрепляется к FragmentManager , а не только после onCreate() .
  • Поддержка Navigation для динамических функциональных модулей теперь зависит от библиотеки доставки гранулированных игр.
  • Safe ARG навигации теперь зависит от плагина Android Gradle Версия 7.3.0. Это означает, что теперь он совместим только с версиями 7.3.0+.

Важные изменения в NavigationUI с 2.5.0

  • При передаче идентификатора навигационного графика в AppBarConfiguration (например, через Menu ), NavigationUI теперь рассматривает только начальное место назначения этого навигационного графа как пункт назначения верхнего уровня, а не неправильно отмечает каждое место назначения в графике как пункт назначения верхнего уровня. Поведение прохождения идентификатора отдельного назначения не изменилось. Эта же функциональность доступна для вашего собственного кода через новую функцию isTopLevelDestination в AppBarConfiguration .
  • Интеграции setupWithNavController в NavigationUI для работы с Top Bar Bar теперь будут анализировать значения R.string для аргументов ReferenceType , найденных в вашем android:label в их строковые значения вместо того, чтобы выводить целое число ресурсов, сгенерированное автоматическим ресурсом.
  • NavigationUI теперь предоставляет журналы, когда не может навигации по выбранной MenuItem .

Версия 2.6.0-RC02

24 мая 2023 г.

androidx.navigation:navigation-*:2.6.0-rc02 выпускается. Версия 2.6.0-RC02 содержит эти коммиты.

Исправления ошибок

  • Исправлена ​​проблема с навигацией в фрагментах, на которой навигация с popUpTo и вытаскивание фрагмента из заднего стека, не воссоздавая его представление, приведет к тому, что Система остановит работу. ( IEB8D4 , B/281726455 )

Версия 2.6.0-RC01

10 мая 2023 г.

androidx.navigation:navigation-*:2.6.0-rc01 выпускается. Версия 2.6.0-RC01 содержит эти коммиты.

Исправления ошибок

  • Исправлена ​​проблема в навигации с фрагментами, в которых удаление фрагмента посредством навигации с popUpTo в его обратном вызове жизненного цикла onResume() может вызвать IllegalStateException . ( I21884 , B/2796444470 )

Версия 2.6.0-BETA01

19 апреля 2023 года

androidx.navigation:navigation-*:2.6.0-beta01 выпускается. Версия 2.6.0-beta01 содержит эти коммиты.

Новые возможности

  • NavBackStackEntry теперь предоставляет пользовательскую реализацию toString . ( IFF00B )

Исправления ошибок

  • При использовании навигации с фрагментами попытка вручную выполнить транзакцию FragmentTransaction , которое добавляет фрагмент в задний стек FragmentManager , теперь бросит IllegalArgumentException . Вы всегда должны добавлять фрагменты через API navigate() . ( I6d38e )
  • Когда есть navigate , которая добавляет запись, и popBackStack , который удаляет ее в той же кадре, полученная верхняя запись в заднем стеке теперь последовательно вернется к RESUMED Lifecycle.State . ( ID8067 , B/276495952 )

Версия 2.6.0-Alpha09

5 апреля 2023 г.

androidx.navigation:navigation-*:2.6.0-alpha09 выпускается. Версия 2.6.0-Alpha09 содержит эти коммиты.

Исправления ошибок

  • Фиксированные проверки на недопустимый маршрут, так что, если NavDestination содержит не нулевой NavArgument , маршрут этого пункта назначения должен содержать заполнители для ARG, названных так же, как и не нулевой NavArgument . ( IC62BF , B/274697949 )
  • DeepLink Navigations, основанные на Action/MimeType теперь не пройдут, если навигационной операции не хватает не нулевого NavArgument требуемого в соответствии с NavDestination , с которым совпадает Action/MimeType . ( IBFA17 , B/271777424 )
  • Когда NavController устанавливает график с тем же маршрутом и направлениями, что и предыдущий график, теперь он правильно заменяет свои текущие узлы графика и назначения спинковых стеков новыми экземплярами. Это исправляет сбой при использовании onLaunchSingleTop без сохранения состояния в навигационной композиции. Это также исправляет ошибку, при которой навигация в пункты назначения, связанные со строительством корневого графа, и неверный задний стек. ( I5bc58 , b/275258161 , b/275407804 )

Версия 2.6.0-Alpha08

22 марта 2023 г.

androidx.navigation:navigation-*:2.6.0-alpha08 выпускается. Версия 2.6.0-Alpha08 содержит эти коммиты.

Новые возможности

  • NavHostFragment теперь позволяет вам получить NavController , как только NavHostFragment прикрепляется к FragmentManager , а не только после onCreate() . ( IC6382 , B/220186282 )

Исправления ошибок

  • Исправлена NullPointerException при выпуске вложенного графика, который включает не нулевой аргумент. ( 6B3581 , B/249988437 )
  • При использовании системы обратно после перемещения с popUpTo , состояние NavController будет выдвинуть в правильную запись. ( I3a8ec , b/2704447657 )
  • FragmentNavigator теперь будет должным образом вспять записи, когда задний стек выпадает через систему назад или popBackStack() и использует ли транзакция эффекты для фрагмента. ( I81bdf )
  • Добавление фрагментов к FragmentManager FragmentNavigator использования навигации больше не вызовет аварии. ( B17204 , B/274167493 )

Обновления зависимости

Версия 2.6.0-Alpha07

8 марта 2023 г.

androidx.navigation:navigation-*:2.6.0-alpha07 выпускается. Версия 2.6.0-Alpha07 содержит эти коммиты.

Исправления ошибок

  • getBackStackEntry , popBackStack , варианты API clearBackStack , которые принимают маршруты, теперь принимают шаблоны маршрута с нулевыми аргументами и нулевыми параметрами запроса ( I22294 , B/269302500 )
  • Исправлена ​​проблема, в которой вызов clearBackStack() из NavController не очистил бы сохраненное состояние в управляющем фрагментами, связанным со стеком очистки. ( IC1CCE , B/271190202 )
  • Исправлена ​​регрессия в 2.6.0-Alpha06, которая вызвала подставку неверного MenuItem в BottomNavigationView при использовании системы обратно между вкладками. ( I634F6 , B/2704447657 )
  • Фиксированная регрессия в 2.6.0-alpha06, которая заставила NavBackStackEntry S не перемещаться в возобновляемое состояние при использовании Animation S. ( IB3589 , B/269646882 )

Версия 2.6.0-Alpha06

22 февраля 2023 года

androidx.navigation:navigation-*:2.6.0-alpha06 выпускается. Версия 2.6.0-Alpha06 содержит эти коммиты.

Новые возможности

  • При предварительном просмотре композиции с NavHost теперь он будет показывать startDestination NavGraph по умолчанию. ( I2b89f )

Изменения API

  • Все перегрузки navigate NavController теперь аннотируются с @MainThread , чтобы убедиться, что они вызываются в главном потоке. ( I2c0b0 , b/263427111 )

Исправления ошибок

  • Исправлена ​​сбой при попытке навигации при использовании динамической навигации фрагментов. ( I3ee29 , b/268360479 )
  • Исправлена ​​ошибка, при которой навигация к другому фрагменту через системную кнопку обратной стороны не обновляет нижнюю панель до правильного выбранного элемента ( IF559F , b/2690444426 )

Известные проблемы

  • При использовании навигации с фрагментами жизненный цикл NavBackStackEntry не может достигать RESUMED при использовании API -интерфейсов Animation . ( B/269646882 )
  • При использовании навигации с фрагментами и навигацией с BottomNavigation , если вы пытаетесь восстановить задний стек с несколькими записями, BottomMenuItem не обновляется правильно. ( B/270447657 )
  • При использовании навигации с фрагментами, после восстановления состояния Lifecycle NavBackStackEntry не DESTROYED при DESTROYED его фрагмента. ( B/270610768 )

Версия 2.6.0-Alpha05

8 февраля 2023 г.

androidx.navigation:navigation-*:2.6.0-alpha05 выпускается. Версия 2.6.0-Alpha05 содержит эти коммиты.

Новые возможности

  • NavController.popBackStack(route) , NavController.getBackStackEntry(route) NavController.clearBackStack(route) ( IEBD28 , IC678C , I3B37B , B/257514373 )
  • FragmentNavigator теперь использует API -интерфейсы перехода при навигации и выпчаве NavBackStackEntries . Это означает, что Lifecycle NavBackStackEntry теперь будет ждать, пока вступление и выйдет на фрагментные спецэффекты, прежде чем перемещать свой последний Lifecycle.State . ( I3cb19 , b/238686802 )
  • DialogFragmentNavigator теперь использует API -интерфейсы перехода при навигации и всплеске NavBackStackEntries . Это означает, что Lifecycle NavBackStackEntry теперь будет ждать, пока Lifecycle DialogFragment перейти к DESTROYED , прежде чем перейти к DESTROYED . ( I53ee5 , b/261213893 )

Изменения API

  • NavigatorState теперь предоставляет API prepareForTransition , позволяющий Navigator S перемещать NavBackStackEntries в промежуточный Lifecycle.State . ( I42c21 , b/238686802 )
  • Теперь вы можете получить доступ к задней части, связанного с NavGraphNavigator или ComposeNavigator через свойство backstack . ComposeNavigator также теперь выявляет обратный вызов onTransitionComplete() , чтобы отметить NavBackStackEntry , который выполнил операцию навигации или popBackStack как завершенное. ( I02062 , i718db , b/257519195 )

Исправления ошибок

  • Навигатор теперь не будет op при использовании API push/popWithTransition , и запись уже обрабатывается. ( IADBFA , B/261213893 )
  • При использовании launchSingleTop с вложенным NavGraph все направления, начиная с оригинального назначения до его startDestination будут только должным образом добавлены в верхнюю часть задней части. ( Id4bea , b/253256629 )
  • Навигация теперь должным образом заменит экземпляр DialogFragment при навигации в тот же пункт назначения, когда флаг launchSingleTop установлен на True. ( I45b5a , b/149572817 )
  • Навигационные Safeargs больше не будут вызывать ошибку компиляции при использовании аргументов, которые стоят ровно 19 символов. ( ID60BC , B/257110095 )

Версия 2.6.0-Alpha04

9 ноября 2022 г.

androidx.navigation:navigation-*:2.6.0-alpha04 выпускается. Версия 2.6.0-Alpha04 содержит эти коммиты.

Новые возможности

  • Пользовательские подклассы NavType теперь могут переопределять serializeAsValue , чтобы сериализовать значение в строку, позволяя как сериализацию, так и десериализацию (через parseValue ) полностью инкапсулировать в класс NavType . StringType теперь переопределяет этот метод, чтобы вызвать Uri.encode на данной String . ( IE5213 , B/247637434 )
  • NavigationUI теперь предоставляет журналы, когда не может навигации по выбранной MenuItem . ( I2af5a , b/247730357 )

Исправления ошибок

  • Глубокие ссылки навигации теперь лениво проанализируются вместо инициализации графика, которая может повысить производительность приложений при запуске. ( Iab0ab )
  • Фиксированный сбой, вызванный навигацией после глубокой связи с пунктом назначения с нулевыми аргументами по умолчанию. ( I51c24 , b/243183636 )

Обновление зависимости

  • Поддержка Navigation для динамических функциональных модулей теперь зависит от библиотеки доставки гранулированных игр. ( IB4DDC )
  • Safe ARG навигации теперь зависит от плагина Android Gradle Версия 7.3.0. Это означает, что теперь он совместим только с версиями 7.3.0+. ( I47e49 )

Версия 2.6.0-Alpha03

24 октября 2022 года

androidx.navigation:navigation-*:2.6.0-alpha03 выпускается. Версия 2.6.0-Alpha03 содержит эти коммиты.

Исправления ошибок

  • Из навигации 2.5.3 : NavHost больше не будет вызывать NoSuchElementException , когда не будет установлено место для сочинения Crossfade . Теперь он просто пропустит композицию. ( IEB46E , B/253299416 )
  • Из навигации 2.5.3 : Исправлена ​​проблема, в которой сохраненное состояние составного состава (например, использование rememberSaveable ) не было забыто и удалялось, когда пункт назначения выскочил из заднего стека. ( I64949 )

Обновления зависимости

Версия 2.6.0-Alpha02

5 октября 2022 г.

androidx.navigation:navigation-*:2.6.0-alpha02 выпускается. Версия 2.6.0-Alpha02 содержит эти коммиты.

Поведение изменяется

  • При передаче идентификатора навигационного графика в AppBarConfiguration (например, через Menu ), NavigationUI теперь рассматривает только начальное место назначения этого навигационного графа как пункт назначения верхнего уровня, а не неправильно отмечает каждое место назначения в графике как пункт назначения верхнего уровня. Поведение прохождения идентификатора отдельного назначения не изменилось. Эта же функциональность доступна для вашего собственного кода через новую функцию isTopLevelDestination в AppBarConfiguration . ( IE936E , B/238496771 )

Исправления ошибок

  • navigation:navigation-fragment теперь зависит от фрагмента версии 1.5.2 . ( I00ba4 )
  • Выбранный элемент меню больше не будет обновляться при перемещении до пункта назначения FloatingWindow , таким как диалог. ( I4cde8 , b/240308330 )

Версия 2.6.0-Alpha01

7 сентября 2022 года

androidx.navigation:navigation-*:2.6.0-alpha01 выпускается. Версия 2.6.0-Alpha01 содержит эти коммиты.

Новые возможности

  • Интеграции setupWithNavController в NavigationUI для работы с Top Bar Bar теперь будут анализировать значения R.string для аргументов ReferenceType , найденных в вашем android:label в их строковые значения вместо того, чтобы выводить целое число ресурсов, сгенерированное автоматическим ресурсом. ( I5f803 , b/167959935 )
  • NavDeepLink теперь поддерживает значения по умолчанию для массивов, что позволяет поддержать повторные параметры запроса, которые будут отображаться в типе массива аргумента. NavType также теперь включает метод по умолчанию, который можно переопределить, чтобы объединить два проанализированных значения. ( ID68C3 , B/209977108 )
  • При использовании точной строки ${applicationId} в качестве заполнителя в app:data и app:dataPattern в элементе деятельности файла навигации XML -файла, заполнитель будет автоматически заполнен с помощью packageName контекста при инфляции. ( Iaabde , b/234223561 )
  • Попытка создать пустой NavDeepLink с использованием DSL navDeepLink Kotlin, теперь приведет к тому, что предупреждение о ворсе, указывающее на то, что глубокая ссылка нуждается в URI, действие и/или миметипе, чтобы быть действительным. ( I08D2F , B/154038883 )

Изменения API

  • Добавлена ​​новая функция расширения NavDestination , чтобы проанализировать динамические метки с аргументами в форме android:label="{arg}" в строку. Поддерживает аргументы ReferenceType , анализируя значения R.string в их строковые значения. ( I07D89 , B/236269380 )

Поведение изменяется

  • arguments Navbackstackentry и arguments , переданные в OnDestinationChangedListener теперь являются лишь копией неизменных аргументов, которые были созданы, когда вы перемещались в пункт назначения. Это означает, что любые изменения, внесенные в эти пучки, не будут отражены в последующих доступах к arguments или другим экземплярам OnDestinationChangedListener . ( I676f5 )

Исправления ошибок

  • Из навигации 2.5.2 : динамическая навигация теперь правильно пытается установить направления деятельности из других модулей, прежде чем навигация на них. ( IA2C16 , B/240292838 )
  • От навигации 2.5.2 : навигация теперь должным образом заменит экземпляр фрагмента при навигации по одному и тому же пункту назначения и установлению флага launchSingleTop в True. ( I5a2f1 , b/237374580 )
  • От навигации 2.5.2 : Фиксированное IllegalStateException , вызванное навигацией до двойного вложенного графика, который делит родителя с новым пусковым пусковым направлением. ( I9f7cb , b/243778589 )

Версия 2.5

Версия 2.5.3

24 октября 2022 года

androidx.navigation:navigation-*:2.5.3 выпущена. Версия 2.5.3 содержит эти коммиты.

Исправления ошибок

  • NavHost больше не вызовет NoSuchElementException , когда нет места назначения для сочинения Crossfade . Теперь он просто пропустит композицию. ( IEB46E , B/253299416 )
  • Исправлена ​​проблема, в которой сохраненное состояние композиции (например, использование rememberSaveable о разветвленных) не было забыто и удалялось, когда пункт назначения был выскочен из заднего стека. ( I64949 )

Версия 2.5.2

7 сентября 2022 года

androidx.navigation:navigation-*:2.5.2 выпущена. Версия 2.5.2 содержит эти коммиты.

Исправления ошибок

  • Динамическая навигация теперь должным образом пытается установить направления деятельности из других модулей, прежде чем навигация на них. ( IA2C16 , B/240292838 )
  • Навигация теперь должным образом заменит экземпляр фрагмента при навигации по одному и тому же пункту назначения и установлению флага launchSingleTop в True. ( I5a2f1 , b/237374580 )
  • Исправлено IllegalStateException , вызванное навигацией на двойной вложенное график, в котором родится родитель с новым пунктом назначения старта. ( I9f7cb , b/243778589 )

Обновление зависимости

Версия 2.5.1

27 июля 2022 года

androidx.navigation:navigation-*:2.5.1 выпускается. Версия 2.5.1 содержит эти коммиты.

Исправления ошибок

  • Navigation Safe Args больше не будут вызывать предупреждения об испаке в сгенерированных классах при использовании пользовательских типов аргументов, которые сохраняются в Bundle . ( Id86ed , b/237725966 )

Обновления зависимости

Версия 2.5.0

29 июня 2022 г.

androidx.navigation:navigation-*:2.5.0 выпускается. Версия 2.5.0 содержит эти коммиты.

Важные изменения с 2.4.0

  • CreationExtras Integration - Navigation теперь имеет возможность обеспечить бездействие ViewModelProvider.Factory через LifeCycle 2.5.0 ' CreationExtras .

Навигация Safeargs

  • Navigation Safe Args повысил зависимость Android Gradle Plugin , чтобы полагаться на 7.0.4 , снизив совместимость для версий AGP до 7.0 .
  • Добавлена ​​поддержка для использования атрибута пространства имен.

Другие изменения

  • API visibleEntries больше не является экспериментальным и обеспечивает функцию для извлечения всех записей, пункт назначения которого в настоящее время видны в соответствии с NavController .

Версия 2.5.0-rc02

15 июня 2022 года

androidx.navigation:navigation-*:2.5.0-rc02 выпущен. Версия 2.5.0-RC02 содержит эти коммиты.

Исправления ошибок

  • Исправлена ​​авария, вызванное быстрым переключением между нижними направлениями при использовании навигационного составления NavHost . ( I3979A , B/234054916 )
  • Navigation SafeArgs больше не будут сбой при использовании applicationIdSuffix и пространства имен, либо без applicationId , либо при различении applicationId и пространства имен. ( I754b1 , b/233119646 )
  • NavArgument теперь имеет пользовательскую функцию toString() чтобы показать внутренние значения аргумента. ( I900a8 )

Версия 2.5.0-rc01

11 мая 2022 года

androidx.navigation:navigation-*:2.5.0-rc01 выпущен. Версия 2.5.0-RC01 содержит эти коммиты.

Новые возможности

  • Добавлено новое правило Lint, чтобы предупредить от размещения элементов <deeplink> внутри <activity> Elements в вашем файле navigation.xml . ( IC15A5 , B/178403185 )

Исправления ошибок

  • Компонируемые прицелы в NavHost и DialogHost в настоящее время расположены в ожидаемом порядке, то есть внутренние композиции расположены перед внешними композищиками. ( I157e6 )
  • Навигационная Safeargs теперь использует PathSensitivity.RELATIVE в ArgumentsGenerationTask для обеспечения перемещения кэша. Это означает, что вход в кеш теперь можно повторно использовать от сборки CI до локальной сборки. ( I5f67c , b/173420454 )
  • Правило Lint UnrememberedGetBackStackEntryDetector Lint было обновлено, чтобы гарантировать, что призыв remember , окружающий вызов getBackStackEntry() , также проходит в объекте NavBackStackEntry в качестве ключа. ( IB7081 , B/227382831 )

Версия 2.5.0-бета01

20 апреля 2022 г.

androidx.navigation:navigation-*:2.5.0-beta01 выпускается. Версия 2.5.0-бета01 содержит эти коммиты.

Исправления ошибок

  • DialogNavigator теперь использует popWithTransition при выполнении вызова dismiss() . Это исправляет условие гонки при использовании ViewModel в dialog пункте назначения, которое приводит к IllegalStateException при отклонении диалога, либо используя систему назад, либо постукивая за пределы диалога для выхода. ( ID7376 , B/2265552301 )

Обновления зависимости

  • Навигация теперь зависит от жизненного цикла 2.5.0-beta01 , исправляя IllegalStateException при гнездовании одного NavHost в другой NavHost на непредровой вкладке нижней навигации при использовании нескольких задних стеков.

Версия 2.5.0-альфа04

6 апреля 2022 г.

androidx.navigation:navigation-*:2.5.0-alpha04 . Версия 2.5.0-Alpha04 содержит эти коммиты.

Изменения API

  • visibleEntries больше не экспериментально. ( I4829f , b/225394514 )

Исправления ошибок

  • Navhost теперь зависит от visibleEntries от NavController , чтобы определить, какие записи сочиняют. Это означает, что при использовании вложенного Navhost внутренний NavHost теперь должен должным образом оживить. ( I4ba2b , b/225394514 )
  • visibleEntries StateFlow предоставленная NavController , теперь основана на состоянии Max Lifecycle, а не в текущем состоянии жизненного цикла. Это означает, что даже если жизненный цикл хоста navController не будет начат, список видимых Entires останется прежним. ( I9e2a8 , b/225394514 )
  • SavedStateViewFactory теперь поддерживает использование CreationExtras даже если он был инициализирован с помощью SavedStateRegistryOwner . Если предоставляются дополнения, инициализированные аргументы игнорируются. ( I6c43b , b/224844583 )
  • NavDeepLink теперь может анализировать URIS с одним параметром запроса без значения. ( I0efe8 , b/148905489 )
  • Пустая строка теперь считается действительными аргументами в глубоких ссылках. ( I70a0d , b/217399862 )
  • Navigation Safe Args больше не будут сбоями при использовании пространств имен, а AndroidManifest.xml не присутствует. ( I17CCF , B/227229815 )

Версия 2.5.0-альфа03

23 февраля 2022 г.

androidx.navigation:navigation-*:2.5.0-alpha03 выпускается. Версия 2.5.0-Alpha03 содержит эти коммиты.

Изменения API

  • Теперь вы можете пройти в CreationExtras by navGraphViewModels чтобы создать ViewModel . ( I29217 , B/217618359 )

Исправления ошибок

  • NavDeepLinks теперь правильно поддерживает закодированные новые линейные символы, встроенные в маршруты/Deep Link URI. ( I513d1 , b/217815060 )
  • CreationExtras теперь будет работать правильно при использовании с NavBackStackEntries для создания ViewModels. ( I69161 , B/217617710 )
  • Safe ARG навигации теперь поддерживает использование пространства имен, определенных в build.gradle вместо пакета в AndroidManifest. ( I659EF , B/217414933 )

Версия 2.5.0-альфа02

9 февраля 2022 года

androidx.navigation:navigation-*:2.5.0-alpha02 выпускается. Версия 2.5.0-Alpha02 содержит эти коммиты.

Исправления ошибок

  • Из навигации 2.4.1 : NavHostFragment теперь правильно установит OnBackPressedDispatcher при использовании подключения для просмотра с вложенными графиками. ( IFBB51 , B/214577959 )
  • Из навигации 2.4.1 : Когда глубокое связывание через несколько вложенных NavGraph S, задний стек теперь будет должным образом включать в себя промежуточные начальные направления. ( I504C0 , B/214383060 )

Версия 2.5.0-альфа01

26 января 2022 года

androidx.navigation:navigation-*:2.5.0-alpha01 выпускается. Версия 2.5.0-Alpha01 содержит эти коммиты.

Новые возможности

Исправления ошибок

  • Исправлена ​​проблема, в которой доступ к ViewModel , созданную через by navGraphViewModels() из фрагмента onCreate() потерпит неудачу с IllegalStateException . ( I8a14d )
  • NavDeepLink S больше не будет излишне декодировать ARGS дважды, что означает, что надлежащие ARG теперь передаются в ваш конечный пункт назначения. ( I31b0a , b/210711399 )

Безопасные аргии

  • Безопасные ARG теперь зависят от Android Gradle Plugin версии 7.0.4. Это означает, что навигационные безопасные ARG больше не будут совместимы с версиями Android Studio до 7.0, но теперь совместим с плагином Android Gradle 7.1.0 и выше. ( I41c88 , b/213086135 , b/207670704 )

Версия 2.4.2

Версия 2.4.2

6 апреля 2022 г.

androidx.navigation:navigation-*:2.4.2 выпущена. Версия 2.4.2 содержит эти коммиты.

Исправления ошибок

  • Перекурированный из навигации 2.5.0-alpha03 : NavDeepLinks теперь правильно поддерживают закодированные новые линейные символы, встроенные в маршруты/Uris Deep Link. ( I513d1 , b/217815060 )
  • Перекурированный из навигации 2.5.0-alpha03 : Navigation Safeargs теперь поддерживает использование пространства имен, определенных в build.gradle вместо пакета в AndroidManifest. ( I659EF , B/217414933 )
  • Перекурированный из навигации 2.5.0-alpha04 : Navigation Safe Args больше не будет сбои при использовании пространств имен, а AndroidManifest.xml не присутствует. ( I17CCF , B/227229815 )
  • Перекурируется из навигации 2.5.0-alpha04 : пустая строка теперь считается действительными аргументами в глубоких ссылках. ( I70a0d , b/217399862 )

Версия 2.4.1

Версия 2.4.1

9 февраля 2022 года

androidx.navigation:navigation-*:2.4.1 выпускается. Версия 2.4.1 содержит эти коммиты.

Исправления ошибок

  • NavHostFragment теперь правильно установит OnBackPressedDispatcher при использовании подключения к вложенным графам. ( IFBB51 , B/214577959 )
  • Когда глубокое связывание через несколько вложенных NavGraph S, задний стек теперь будет правильно включать в себя промежуточные начальные направления. ( I504C0 , B/214383060 )
  • Перекурированный из навигации 2.5.0-alpha01 : Исправлена ​​проблема, в которой доступ к ViewModel, созданную через by navGraphViewModels() из фрагмента onCreate() будет провалиться с IllegalStateException . ( I8a14d )
  • Перекурированный из навигации 2.5.0-alpha01 : NavDeepLink S больше не излишне декодирует ARGS, что означает, что правильно декодированные ARG теперь передаются в ваш конечный пункт назначения. ( I31b0a , b/210711399 )
  • Перекурируется из навигации 2.5.0-alpha01 : безопасные ARG теперь зависит от Android Gradle Plugin Версия 7.0.4. This means that Navigation Safe Args will no longer be compatible with Android Studio versions prior to 7.0, but is now compatible with Android Gradle Plugin 7.1.0 and higher. ( I41c88 , b/213086135 , b/207670704 )

Версия 2.4.0

Версия 2.4.0

January 26, 2022

androidx.navigation:navigation-*:2.4.0 is released. Версия 2.4.0 содержит эти коммиты.

Важные изменения с версии 2.3.0

  • All Navigation artifacts have been rewritten in Kotlin. This has improved the nullability of classes using generics (such as NavType subclasses). All Kotlin extension functions that used to be part of the -ktx artifacts have been moved to their respective main artifacts. The -ktx artifacts will continue to be published, but are completely empty.
  • The navigation-fragment artifact now contains a prebuilt implementation of a two pane layout via the new AbstractListDetailFragment . This fragment uses a SlidingPaneLayout to manage a list pane (which your subclass provides) and a detail pane, which uses a NavHostFragment as its implementation, as seen in our example implementation .
  • The currentBackStackEntryAsFlow() method on NavController provides a Flow that emits whenever the current NavBackStackEntry changes. This flow can be used as an alternative to manually managing an OnDestinationChangedListener .
  • NavController now offers the ability to retrieve a list of all visible NavBackStackEntry instances as a StateFlow via the experimental visibleEntries property.
  • It is now possible to extend the NavType class to create custom NavTypes. Custom types are supported only when building your navigation graph programmatically, such as via the Navigation Graph Kotlin DSL .
  • Navigation now provides findStartDestination() and getHierarchy() APIs that can be used to help implement custom NavigationUI. findStartDestination() is an extension function on NavGraph that will locate the actual start destination that will be displayed when you navigate to the graph, even if the startDestination is itself a nested NavGraph . getHierarchy() is a function on NavDestination that can be used to verify if a given destination is within the hierarchy of another.

    val matchingRoute: Boolean = destination.hierarchy.any { it.route == routeToFind }
    
  • NavigationUI methods that took a BottomNavigationView have been updated to instead take its superclass introduced in Material 1.4.0 , NavigationBarView . This allows these methods to be used with the NavigationRailView .

  • When inflating an <action> element via XML, animation attributes can use attributes pulled from your theme using the app:enterAnim="?attr/transitionEnter" syntax.

  • Safe Args now generates a fromSavedStateHandle() method for each NavArgs class. ( #122 , b/136967621 )

    class HomeViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
      // Create a HomeDestinationArgs class with type safe accessors for each argument
      // defined on your destination
      private val args = HomeDestinationArgs.fromSavedStateHandle(savedStateHandle)
    }
    

Navigation Routes and the Kotlin DSL

Previous versions of Navigation relied on each destination having a constant integer ID that would uniquely identify it from its sibling destinations and allow you to navigate() to that destination either directly or via an action. While this continues to be valid and useful, particularly in cases where you are defining your navigation graph in XML and can use auto-generated R.id constants or Safe Args (which uses those constants to generate code at build time), this system of unique integers did not capture the semantic meaning and expressiveness needed to support fully dynamic graphs built programmatically at runtime via the Navigation Kotlin DSL .

This release introduces a new option for uniquely identifying a destination in a navigation graph by its route . A route is a String that defines the unique path to a destination. All Kotlin DSL methods that took a destination ID are now deprecated and replaced with an equivalent API that takes a route.

Each route should be treated as the 'path' part of a Uri that defines that destination, eg, home , profile/{userId} , profile/{userId}/friends , etc. When the identity of a destination is associated with a specific piece of content, those dynamic arguments should be part of the route, following the same rules as implicit deep links .

All NavController APIs that used to only take an ID now have an overload that takes a route String . This includes navigate() , popBackStack() , popUpTo() , and getBackStackEntry() .

This has had some API implications:

  • The popUpTo Kotlin property on the Kotlin DSL has been deprecated in favor of popUpToId .
  • The getStartDestination() API has been deprecated in favor of getStartDestinationId() .

Unlike when navigating by ID, navigating by route follows the same rules as implicit deep links in that you can directly navigate to any destination in any nested graph, ensuring that these routes are usable in multi-module projects without explicitly adding an externally visible deep link to each destination.

Navigation Compose

The navigation-compose artifact provides integration between the Navigation Component and Jetpack Compose . It uses @Composable functions as the destinations in your application.

This release provides:

  • A NavHost composable that allows you to construct your navigation graph via a Kotlin DSL, using composable and dialog destinations, plus support for optional Navigators such as those from Accompanist Navigation Material .
  • Mandatory support for crossfading between destinations. Accompanist Navigation Animation can be used to control the enter and exit transitions using experimental Compose APIs.
  • Scoping of a Lifecycle to each composable destination. Each destination only reaches the RESUMED state when any entering transitions finish and immediately drops to STARTED when any exiting transitions start, thus allowing you to avoid all IllegalStateException and multi-touch issues by only triggering a navigate call when the Lifecycle is RESUMED .
  • Scoping of ViewModel (via the viewModel() API of Lifecycle ViewModel Compose 2.4.0 or hiltViewModel() of Hilt Navigation Compose 1.0.0 at the destination level, providing a scope that survives configuration changes and being on the back stack (when your Composable content is otherwise disposed) and a signal in the ViewModel's onCleared() that indicates the permanent disposal and cleaning up of state associated with that NavBackStackEntry .
  • Scoping of rememberSaveable state at a destination level, ensuring that all composable state is saved and restored automatically when you return to a destination.
  • Full support for saving and restoring the state of the NavController and its destination's state after process death and recreation.
  • Automatic integration with the system back button.
  • Support for passing arguments, attaching deep links to destinations, and returning a result to previous destinations.

  • Compose specific helpers in rememberNavController() and currentBackStackEntryAsState() to allow hoisting state and connecting the NavController to composables outside of the NavHost (such as a bottom navigation bar).

val navController = rememberNavController()
Scaffold { innerPadding ->
    NavHost(navController, "home", Modifier.padding(innerPadding)) {
        composable("home") {
            // This content fills the area provided to the NavHost
            HomeScreen()
        }
        dialog("detail_dialog") {
            // This content will be automatically added to a Dialog() composable
            // and appear above the HomeScreen or other composable destinations
            DetailDialogContent()
        }
    }
}

See the Compose Navigation guide for more information.

Multiple back stacks

The NavController is responsible for managing the back stack of destinations, adding destinations to the back stack when you navigate() to them and removing them when you call popBackStack() or trigger the system back button. The existing NavOptions class and the integration into <action> elements in the navigation graph XML has been expanded to support saving and restoring the back stack.

As part of this change, the NavigationUI methods of onNavDestinationSelected() , BottomNavigationView.setupWithNavController() and NavigationView.setupWithNavController() now automatically save and restore the state of popped destinations, enabling support for multiple back stacks without any code changes. When using Navigation with Fragments, this is the recommended way to integrate with multiple back stacks.

The underlying APIs for saving and restoring the state are exposed via a number of surfaces:

  • In Navigation XML, the <action> element can now use the boolean attributes of app:popUpToSaveState and app:restoreState to save the state of any destinations popped via app:popUpTo and restore the state associated with the destination passed as the app:destination :

    <action
      android:id=”@+id/swap_stack”
      app:destination=”@id/second_stack”
      app:restoreState=”true”
      app:popUpTo=”@id/first_stack_start_destination”
      app:popUpToSaveState=”true” />
    
  • In the navOptions Kotlin DSL , you can add the restoreState boolean property and the saveState boolean property on the popUpTo builder :

    // Use the navigate() method that takes a navOptions DSL Builder
    navController.navigate(selectedBottomNavRoute) {
      launchSingleTop = true
      restoreState = true
      popUpTo(navController.graph.findStartDestination().id) {
        saveState = true
      }
    }
    
  • In manually building a NavOptions object via the NavOptions.Builder , you can use the setRestoreState() and new overload to setPopUpTo() that takes an additional saveState parameter.

    NavOptions navOptions = new NavOptions.Builder()
      .setLaunchSingleTop(true)
      .setRestoreState(true)
      .setPopUpTo(NavGraph.findStartDestination(navController.getGraph()).getId(),
        false, // inclusive
        true) // saveState
      .build();
    navController.navigate(selectedBottomNavId, null, navOptions);
    
  • Programmatic calls to popBackStack() can now include an additional saveState parameter.

  • You can use the clearBackStack() method to clear any state that was saved with popBackStack() or popUpToSaveState .

In all cases, the NavController will save and restore the state of each NavBackStackEntry , including any navigation destination scoped ViewModel instances. The Navigator APIs have been updated to enable each Navigator to support saving and restoring their own state.

Изменения в поведении

  • NavDeepLinkBuilder now adds PendingIntent.FLAG_IMMUTABLE to the PendingIntent returned by createPendingIntent() , ensuring that this API works as expected when targeting Android 12.
  • Navigation now depends on Lifecycle 2.3.1 and now marks setGraph() , popBackStack() , navigateUp() , and navigate() , the methods that update the NavBackStackEntry Lifecycle , as @MainThread , aligning Navigation with the main thread enforcement introduced in Lifecycle 2.3.0 .
  • Deep links now verify that all required arguments (those without default values) are present in the Uri .
  • NavDeepLink parsed arguments now consider pound signs in the same way as question marks as a separator between path segments, preventing an argument from spanning across the pound sign.
  • When generating actions, Kotlin code generated from Safe Args now puts arguments without default values before those with default values as parameters.
  • When generating arguments, Safe Args now puts parameters without default values before those with default values.
  • Safe-Args now depends on Android Gradle Plugin 4.2.0. This means you should no longer get the using applicationIdTextResource warning.

Известные проблемы

  • Fixed in Navigation 2.5.0-alpha01 : accessing a ViewModel created via by navGraphViewModels() from a Fragment's onCreate() will fail with an IllegalStateException . ( b/213504272 )
  • Fixed in Navigation 2.5.0-alpha01 : Safe Args 2.4.0 is incompatible with Android Gradle Plugin 7.1.0 and higher. ( b/213086135 )
  • Deep linking with multiple nested nav graphs doesn't correctly create the full backstack. ( b/214383060 )

Версия 2.4.0-rc01

15 декабря 2021 г.

androidx.navigation:navigation-*:2.4.0-rc01 is released. Версия 2.4.0-rc01 содержит эти коммиты.

Изменения в поведении

  • NavDeepLink parsed arguments now consider pound signs in the same way as question marks as a separator between arguments. ( I21309 , b/180042703 )

Исправления ошибок

  • Deeplinks will no longer ignore arguments with values that are the same as the name of the placeholder. ( If8017 , b/207389470 )
  • NavController will no longer crash when popping a nested destination using transitions after the NavController has been restored. ( I0f7c9 , b/205021623 )
  • The error message when using an invalid startDestination will now default to the start destination's route if one is available. ( I86b9d , b/208041894 )

Navigation Compose Bug Fixes

  • Fixed potential crash caused by fast switching between the start destination and another destination using bottom nav menu items. ( Ic8976 , b/208887901 )
  • Dialog destination are now properly restored on top of the screen after config changes or process death. ( I4c0dc , b/207386169 )
  • Fixed an issue where attempting to retrieve a ViewModel from a dialog's NavBackStackEntry would fail when the dialog was dismissed. ( I6b96d , b/206465487 )
  • Fixed an issue when using activity destinations with Navigation Compose's NavHost that would result in infinite recompositions. ( I8f64c )
  • Fixed a leak in Navigation Compose where it was holding on to a reference of the old activity after a config change or process death. ( I4efcb , b/204905432 )

Safe Args Bug Fixes

  • SafeArgs no longer crashes when attempting to restore custom parcelable arrays after process death. ( I618e8 , b/207315994 )
  • Fixed a bug in safe args that would not allow boolean arrays to have a null value. ( I8c396 , b/174787525 )

Version 2.4.0-beta02

November 3, 2021

androidx.navigation:navigation-*:2.4.0-beta02 is released. Version 2.4.0-beta02 contains these commits.

Изменения API

  • The handling of both explicit and implicit deep links now automatically adds the saveState flag when navigating to another graph, ensuring that code such as NavigationUI.setupWithNavController and code using multiple back stacks works as expected. ( Ic8807 )

Behavior Changes

  • Deep link patterns are now compiled lazily in NavDeepLink instead of during inflation. This should improve the inflation time of navigation graphs that include deep links. ( b8d257 , b/184149935 )

Исправления ошибок

  • Fixed an issue where NavBackStackEntries were being pushed down to Lifecycle.State.CREATED after moving to Lifecycle.State.STARTED when the NavHost is added directly to the activity's setContent() . ( Ia5ac1 , b/203536683 )
  • Fixed a race condition where popping a DialogFragment destination off of the back stack before the dialog was actually shown would not actually dismiss the dialog, resulting in a crash when the errant dialog was manually dismissed by the user. ( I687e5 )
  • Fixed an issue where the onNavDestinationSelected API on NavigationUI would return true even if you didn't actually navigate() to that navigation graph. It now uses the same logic used internally by setupWithNavController to only select the MenuItem associated with the current destination using the hierarchy of the destination. ( I2b053 )

Версия 2.4.0-бета01

27 октября 2021 г.

androidx.navigation:navigation-*:2.4.0-beta01 is released. Версия 2.4.0-beta01 содержит эти коммиты.

Новые возможности

  • You can now use by navGraphViewModel with a route as an alternative to using an ID so as to better support using the Navigation Kotlin DSL with Fragments. ( I901e3 , b/201446416 )

Изменения API

  • The visibleEntries API is now experimental. ( I93f6f )

Исправления ошибок

  • ViewModels will no longer be destroyed when transitions are interrupted by navigating back and forth between the same screens ( Id52d8 , b/200817333 )
  • Nullable NavDeepLink arguments no longer require a default value when adding deep links to NavDestination s. ( I5aad4 , b/201320030 )
  • NavBackStackEntries now with different Lifecycles are not longer considered equal. This means NavHost will properly recompose all destinations when doing navigation with singleTop and when reselecting bottom menu items. ( I1b351 , b/196997433 )
  • Fixed an issue with AbstractListDetailFragment that caused the layout_width and layout_weight attributes on the list pane returned by onCreateListPaneView() to be incorrectly handled or ignored. ( f5fbf3 )
  • The visual state of dialog destinations now correctly stays in sync with the DialogFragmentNavigator 's state. This means that manually calling the asynchronous dismiss() API for DialogFragment now properly clears all dialog destinations above the now dismissed dialog. This does not affect cases where you use popUpTo or popBackStack() to dismiss your dialog. ( I77ba2 )
  • AbstractAppBarOnDestinationChangedListener now has clearer error messaging for onDestinationChanged() . ( Ie742d )

Version 2.4.0-alpha10

29 сентября 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha10 is released. Version 2.4.0-alpha10 contains these commits.

Новые возможности

  • NavController now offers the ability to retrieve a list of all visible NavBackStackEntry instances via the visibleEntries StateFlow ( Ia964e )
  • rememberNavController() now takes a optional set of Navigator instances that will be added to the returned NavController to better support optional Navigators such as those from Accompanist Navigation Material . ( I4619e )

Исправления ошибок

  • Dynamic Navigation will no longer crash when the Activity is recreated. ( Ifa6a3 , b/197942869 )
  • Fixed an issue with the system back button that occurs only after popping back to a composable destination that contains a NavHost . ( 3ed148 , b/195668143 )
  • SafeArgs now generates the arguments for fromBundle() and fromSavedStateHandle() in the proper parameter order. ( I824a8 , b/200059831 )

Version 2.4.0-alpha09

September 15, 2021

androidx.navigation:navigation-*:2.4.0-alpha09 is released. Version 2.4.0-alpha09 contains these commits.

Новые возможности

  • You can now use the clearBackStack() method to clear any state that was saved with popBackStack() or popUpToSaveState . ( I80a0f )
  • You can now pass in a list of arguments and/or deep links to your nested navigation graph's builder and they will automatically be added to the resulting graph. ( I8a470 , b/182545357 )

Изменения API

  • The navArgument Kotlin DSL function is now part of navigation-common instead of navigation-compose . This will require updating imports to continue to use this function. ( I1d095 )

Behavior Changes

  • When generating arguments, Safe Args now puts parameters without default values before those with default values. ( I89709 , b/198493585 )

Исправления ошибок

  • When using Navigation Compose, NavGraphs will only be DESTROYED once all their children are DESTROYED . ( I86552 , b/198741720 )
  • Nullable NavDeepLink arguments no longer require a default value. ( Ia14ef , b/198689811 )
  • Calling setGraph() with a new graph will now also clear any saved back stacks in addition to its previous behavior of popping the back stack. ( I97f96 )
  • Fixed an issue where OnDestinationChangedListener instances and the currentBackStackEntryFlow were not notified when using launchSingleTop . ( Iaaebc )

Обновления зависимости

Version 2.4.0-alpha08

1 сентября 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha08 is released. Version 2.4.0-alpha08 contains these commits.

Новые возможности

  • It is now possible to extend the NavType class to create custom NavTypes. Custom types are supported only when building your navigation graph programmatically, such as via the Navigation Graph Kotlin DSL . ( I78440 , b/196871885 )

Behavior Changes

  • When generating actions, Kotlin code generated from Safe Args now puts arguments without default values before those with default values as parameters. ( Idb697 , b/188855904 )
  • Deep links now verify that all required arguments (those without default values) are present in the Uri . ( #204 , b/185527157 )

Исправления ошибок

  • Using getBackStackEntry and previousBackStackEntry inside composable(), in conjunction with remember() , will no longer cause an exception for no destination being on the back stack. ( I75138 , b/194313238 )
  • Navigation Compose now properly recomposes when changing back stack arguments and using launchSingleTop=true . ( Iebd69 , b/186392337 )
  • There will no longer be an ArrayIndexOutOfBoundsException when calling setGraph with a graph with 13 or 29 destinations. ( I1a9f1 , b/195171984 )
  • The SafeArgs java generator should no longer cause lint warnings when generating Args classes. ( I1a666 , b/185843837 )

External Contribution

  • Thanks ospixd for ensuring that deep links verify that all required arguments (those without default values) are present in the Uri . ( #204 , b/185527157 )

Version 2.4.0-alpha07

18 августа 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha07 is released. Version 2.4.0-alpha07 contains these commits.

Исправления ошибок

  • Navigation Compose now properly saves state after configuration changes and when changing graphs while using the multiple back stack feature. ( If5a3d , b/195141957 )
  • Re-selecting the same tab when using navigation compose with multiple back stacks will no longer result in a blank screen. ( I860dc , b/194925622 )
  • NavHost now observes for changes in the Lifecycle.State of NavBackStackEntry s which means using a NavHost in a fragment now will properly be recomposed as the lifecycle changes instead of resulting in a blank screen. ( I4eb85 , b/195864489 )
  • Fixed an issue where dismissing a DialogFragment would not correctly update the NavController state after recreating your activity (ie, after a configuration change). ( Icd72b )
  • Fixed an issue where popping a dialog destination would not update the NavController's system back button handling, potentially causing the NavController to intercept the back button even though it does not have any back stack to pop. ( If3b34 )
  • Safe-args now automatically generates a toSavedStateHandle method for arguments which can be used to test your ViewModel code. ( If1e2d , b/193353880 )

Version 2.4.0-alpha06

August 4, 2021

androidx.navigation:navigation-*:2.4.0-alpha06 is released. Version 2.4.0-alpha06 contains these commits.

Изменения API

  • The requireSlidingPaneLayout() and requireDetailPaneNavHostFragment() methods on AbstractListDetailFragment have been renamed to getSlidingPaneLayout() and getDetailPaneNavHostFragment() , respectively. ( I34a08 )

Behavior Changes

  • When navigating with animations (like Crossfade ), the new destination's Lifecycle will now only reach the RESUMED when the animation completes. ( If0543 , b/172112072 , b/194301889 )
  • Navigation Compose's NavHost now sets the graph as part of the first composition. ( Ieb7be )

Исправления ошибок

  • Popping the last destination of a navigation graph no longer throws a ClassCastException . ( If0543 , b/172112072 , b/194301889 )
  • Fixed a NullPointerException that would occur when adding a deep link without a Uri and navigating via a route or deep link. ( 938a0c , b/193805425 )
  • Fixed an issue in Navigation Compose where a deep linked NavBackStackEntry would not reach the RESUMED state. ( I192c5 )
  • Fixed an issue where popping a dialog destination would not update the NavController's system back button handling, potentially causing the NavController to intercept the back button even though it does not have any back stack to pop. ( aosp/1782668 )

Version 2.4.0-alpha05

21 июля 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha05 is released. Version 2.4.0-alpha05 contains these commits.

Behavior Changes

  • Navigation Compose's NavHost now always uses Crossfades when navigating through destinations. ( I07049 , b/172112072 )
  • You can now make changes to the graph of a NavHost. Graphs with the same startDestination and destinations in the graph will be considered equal and will not clear the NavController back stack. ( I0b8db , b/175392262 )

Исправления ошибок

  • Fixed a NoSuchElementException when calling popBackStack() from within a LifecycleObserver attached to a NavBackStackEntry caused by reentrant updates to the NavController's state. ( I64621 )
  • AbstractListDetailFragment now allows SlidingPaneLayout to be completely stripped from your APK when AbstractListDetailFragment is not used. ( I611ad )
  • NavGraph and NavDestination now override the equals method so two objects with the same values will be considered equal. ( I166eb , b/175392262 )

Version 2.4.0-alpha04

1 июля 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha04 is released. Version 2.4.0-alpha04 contains these commits.

Новые возможности

  • The navigation-fragment artifact now contains a prebuilt implementation of a two pane layout via the new AbstractListDetailFragment . This fragment uses a SlidingPaneLayout to manage a list pane (which your subclass provides) and a detail pane, which uses a NavHostFragment as its implementation, as seen in our example implementation . ( Iac4be , b/191276636 )
  • The NavHost of the navigation-compose artifact now supports dialog destinations in addition to composable destinations. These dialog destinations will each be shown within a Composable Dialog , floating above the current composable destination. ( I011d0 )
val navController = rememberNavController()
    Scaffold { innerPadding ->
        NavHost(navController, "home", Modifier.padding(innerPadding)) {
            composable("home") {
                // This content fills the area provided to the NavHost
                HomeScreen()
            }
            dialog("detail_dialog") {
                // This content will be automatically added to a Dialog() composable
                // and appear above the HomeScreen or other composable destinations
                DetailDialogContent()
            }
        }
    }

Изменения API

  • The add function in NavigatorState has been renamed to push . All current calls to add() will need to be changed to push(). ( Ie89fc , b/172112072 )
  • Custom Navigator instances can now use the pushWithTransaction and popWithTransition APIs on NavigatorState to push or pop a destination asynchronously. Note that this APIs are not yet used by any of the included navigators. ( Ic4d7c , b/172112072 )

Behavior Changes

  • NavDeepLinkBuilder now adds PendingIntent.FLAG_IMMUTABLE to the PendingIntent returned by createPendingIntent() , ensuring that this API works as expected when targeting Android 12. ( If8c52 )

Исправления ошибок

  • Fixed an issue with <include-dynamic> where arguments passed to the graph would not be correctly passed to the dynamically included graph. ( I3e115 )
  • Fixed a NullPointerException when navigating to a destination using a string[] argument with a default value of @null . ( I1fbe8 )
  • Add ProGuard rules for @Navigator.Name , fixing issues when using R8 3.1 full mode. ( I2add9 , b/191654433 )
  • SafeArgs will no longer fail when building your app with Kotlin versions before 1.5.0 . ( Icd1ff , b/190739257 )

Версия 2.4.0-альфа03

16 июня 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha03 is released. Версия 2.4.0-alpha03 содержит эти коммиты.

Исправления ошибок

  • Fixed an issue where two navigate() calls were needed to navigate to an included dynamic graph. ( I7785c , b/188859835 )
  • Fixed a regression introduced in Navigation 2.4.0-alpha01 where setupActionBarWithNavController() would not properly remove the Up icon when you are on a top level destination. ( I5d443 , b/189868637 )
  • Fixed an IllegalStateException when calling popBackStack() after previously popping the root graph of the NavController. ( I2a330 , b/190265699 )
  • ProGuard rules for by navArgs() now properly apply when using navigation-common or any artifacts that depend on it. ( I68800 , b/190082521 )
  • An OnDestinationChangedListener that calls navigate() the first time it receives a callback now properly get a second callback with the destination it navigated to. ( Ie5f9e , b/190228815 )
  • Safe Args no longer crashes when using it with dynamic feature modules and AGP 7.0+. ( I69518 , b/189966576 )

Известная проблема

  • Safe Args will fail with an Unable to find method ''java.lang.String kotlin.text.CarsKt.titleCase(char, java.util.Locale)'' error when using Gradle 6.7.0 due to a dependency on an older version of Kotlin. This can be worked around by updating to use Gradle 7.0. ( b/190739257 )

Версия 2.4.0-альфа02

2 июня 2021 года

androidx.navigation:navigation-*:2.4.0-alpha02 is released. Версия 2.4.0-alpha02 содержит эти коммиты.

Новые возможности

  • Routes are now supported for Activity, Fragment and Dialog destinations, as well as throughout the DynamicNavigation Kotlin DSL. ( Ib5544 , Ia617b , I22f96 , b/188914648 , b/188901565 )
  • NavigationUI has temporarily added experimental APIs to allow opting out of saving your state. While always saving the state is the correct behavior, there are still uses of deprecated libraries (ie retained fragments), that cannot be supported when saving the state so this gives an opportunity for apps to slowly convert away from any unsupported APIs. ( Idf93c )
  • Navigation now provides findDestination() and getHierarchy() APIs that can be used to help implement custom NavigationUI. findDestination() is an extension function on NavGraph that will locate a destination within the graph. getHierarchy() is a function on NavDestination that can be used to verify if a given destination is within the hierarchy of another.( I2932f , b/188183365 )

    val matchingRoute: Boolean = destination.hierarchy.any { it.route == routeToFind }
    
  • NavigationUI methods that took a BottomNavigationView have been updated to instead take its superclass introduced in Material 1.4.0 , NavigationBarView . This allows these methods to be used with the NavigationRailView . ( Ib0b36 , b/182938895 )

  • When inflating an <action> element via XML, animation attributes can use attributes pulled from your theme using the app:enterAnim="?attr/transitionEnter" syntax. ( I07bc1 , b/178291654 )

Изменения API

Исправления ошибок

  • DialogFragmentNavigator now uses the NavigatorState.pop() API to inform the NavController when a dialog is dismissed by hitting the system back button or clicking outside of it, ensuring that the NavController state is always in sync with the Navigator's state. ( I2ead9 )
  • Navigation no longer gives a ConcurrentModificationException when using manipulating the list of OnDestinationChangedListeners from with an onDestinationChanged callback. ( Ib1707 , b/188860458 )

  • Safe Args no longer crashes when attempting to generate direction properties in Kotlin. ( Id2416 , b/188564435 )

  • The setId method on NavDestination is now properly annotated with @IdRes , so it only accepts resource ids. ( I69b80 )

  • The int parameter of findNode is now resId instead of resid . ( I7711d )

Dependency Update

  • Safe-Args now depends on Android Gradle Plugin 4.2.0. This means you should no longer get the using applicationIdTextResource warning. ( I6d67b , b/172824579 )

Версия 2.4.0-альфа01

May 18, 2021

androidx.navigation:navigation-*:2.4.0-alpha01 is released. Версия 2.4.0-alpha01 содержит эти коммиты.

Новые возможности

  • The currentBackStackEntryAsFlow() method on NavController provides a Flow that emits whenever the current NavBackStackEntry changes. This flow can be used as an alternative to manually managing an OnDestinationChangedListener . ( I19c4a , #89 , b/163947280 )

Multiple back stacks

The NavController is responsible for managing the back stack of destinations, adding destinations to the back stack when you navigate() to them and removing them when you call popBackStack() or trigger the system back button. The existing NavOptions class and the integration into <action> entries in the navigation graph XML has been expanded to support saving and restoring the back stack. ( b/80029773 )

As part of this change, the NavigationUI methods of onNavDestinationSelected() , BottomNavigationView.setupWithNavController() and NavigationView.setupWithNavController() now automatically save and restore the state of popped destinations, enabling support for multiple back stacks without any code changes. When using Navigation with Fragments, this is the recommended way to integrate with multiple back stacks. ( Ie07ca )

The underlying APIs for saving and restoring the state are exposed via a number of surfaces:

  • In Navigation XML, the <action> element can now use the boolean attributes of app:popUpToSaveState and app:restoreState to save the state of any destinations popped via app:popUpTo and restore the state associated with the destination passed as the app:destination :

    <action
      android:id=”@+id/swap_stack”
      app:destination=”@id/second_stack”
      app:restoreState=”true”
      app:popUpTo=”@id/first_stack_start_destination”
      app:popUpToSaveState=”true” />
    
  • In the navOptions Kotlin DSL , you can add the restoreState boolean property and the saveState boolean property on the popUpTo builder :

    // Use the navigate() method that takes a navOptions DSL Builder
    navController.navigate(selectedBottomNavRoute) {
      launchSingleTop = true
      restoreState = true
      popUpTo(navController.graph.startDestinationId) {
        saveState = true
      }
    }
    
  • In manually building a NavOptions object via the NavOptions.Builder , you can use the setRestoreState() and new overload to setPopUpTo() that takes an additional saveState parameter.

    NavOptions navOptions = new NavOptions.Builder()
      .setLaunchSingleTop(true)
      .setRestoreState(true)
      .setPopUpTo(navController.getGraph().getStartDestinationId(),
        false, // inclusive
        true) // saveState
      .build();
    navController.navigate(selectedBottomNavId, null, navOptions);
    
  • Programmatic calls to popBackStack() can now include an additional saveState parameter.

In all cases, the NavController will save and restore the state of each NavBackStackEntry , including any navigation destination scoped ViewModel instances. The Navigator APIs have been updated to enable each Navigator to support saving and restoring their own state.

The ComposeNavigator used for composable destinations in Navigation Compose and the FragmentNavigator and DynamicFragmentNavigator used for <fragment> destinations in Navigation with Fragments have both been updated to use the new Navigator APIs and support saving and restoring state.

Navigation Routes

A route is a String that uniquely identifies a destination. While previously only used in Navigation Compose , this concept has now graduated to become a part of the core Navigation APIs. This provides an alternative to using integer IDs when constructing your graph through the Navigation Kotlin DSL . ( b/172823546 )

All APIs that used to only take an ID now have an overload that takes a route String . This includes navigate() , popBackStack() , popUpTo() , and getBackStackEntry() .

This has had some API implications:

  • The popUpTo kotlin property on the Kotlin DSL has been deprecated in favor of popUpToId . ( I59c73 , b/172823546 )
  • The getStartDestination() API has been deprecated in favor of getStartDestinationId() . ( I0887f , b/172823546 )

For developers upgrading from previous versions of Navigation Compose to Navigation Compose 2.4.0-alpha01 , this means that the following imports on extension methods are no longer necessary and should be removed:

import androidx.navigation.compose.navigation
import androidx.navigation.compose.createGraph
import androidx.navigation.compose.getBackStackEntry
import androidx.navigation.compose.navigate
import androidx.navigation.compose.popUpTo

The KEY_ROUTE argument has been replaced with the route property on NavDestination , allowing you to call navBackStackEntry.destination.route directly.

Изменения API

  • All Navigation artifacts have been rewritten in Kotlin. This has improved the nullability of classes using generics (such as NavType subclasses). All Kotlin extension functions that used to be part of the -ktx artifacts have been moved to their respective main artifacts. The -ktx artifacts will continue to be published, but are completely empty. ( b/184292145 )
  • NavDeepLinkBuilder now supports adding multiple distinct destinations to the generated back stack. ( I3ee0d , b/147913689 )
  • Add factory functions for DynamicNavHostFragment ( Icd515 , b/175222619 )
  • The unique ID of a NavBackStackEntry is now exposed as part of its public API. ( Ie033a )
  • The name and argument fields and destructuring functions of NamedNavArgument are now public. ( #174 , b/181320559 )
  • Introduced a new NavBackStackEntry#provideToCompositionLocals extension that provides the NavBackStackEntry to the relevant composition locals. ( #175 , b/187229439 )

Safe Args

  • Safe Args now generates a fromSavedStateHandle() method for each NavArgs class. ( #122 , b/136967621 )

    class HomeViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
      // Create a HomeDestinationArgs class with type safe accessors for each argument
      // defined on your destination
      private val args = HomeDestinationArgs.fromSavedStateHandle(savedStateHandle)
    }
    
  • Updated Safe Args to depend on KotlinPoet 1.8.0 . ( #172 , b/183990444 )

Behavior Changes

  • Navigation now depends on Lifecycle 2.3.1 and now marks setGraph() , popBackStack() , navigateUp() , and navigate() , the methods that update the NavBackStackEntry Lifecycle , as @MainThread , aligning Navigation with the main thread enforcement introduced in Lifecycle 2.3.0 . ( b/171125856 )
  • Parsing Enum arguments from deep links is now case insensitive, allowing a deep link like http://www.example.com/red to match a www.example.com/{color} deep link even when the enum has the value of RED . ( #152 , b/135857840 )

Compose Compatibility

  • androidx.navigation:navigation-compose:2.4.0-alpha01 is only compatible with Compose version 1.0.0-beta07 and above.

Исправления ошибок

  • Fixed an issue where trailing argument placeholders would take precedence over deep links that have a matching exact suffix. ( #153 , b/184072811 )
  • NavHostFragment now supports custom Navigators that use the same @Navigator.Name("dialog") as the default DialogFragmentNavigator . ( Ib1c2c , b/175979140 )
  • Improved the behavior of NavigatorProvider#addNavigator to ensure that calling it repeatedly with the same instance does not cause issues. ( #176 , b/187443146 )

External Contributions

  • Thanks simonschiller for building support for Safe Args generating a fromSavedStateHandle() method for each NavArgs class. ( #122 , b/136967621 )
  • Thanks Bradleycorn for making parsing Enum arguments from deep links case insensitive. ( #152 , b/135857840 )
  • Thanks osipxd for fixing an issue where trailing argument placeholders would take precedence over deep links that have a matching exact suffix. ( #153 , b/184072811 )
  • Thanks tatocaster for updating Safe Args to depend on KotlinPoet 1.8.0 . ( #172 , b/183990444 )
  • Thanks jossiwolf for making the name and argument fields and destructuring functions of NamedNavArgument public. ( #174 , b/181320559 )
  • Thanks jossiwolf for introducing a new NavBackStackEntry#provideToCompositionLocals extension that provides the NavBackStackEntry to the relevant composition locals. ( #175 , b/187229439 )
  • Thanks jossiwolf for improved the behavior of NavigatorProvider#addNavigator to ensure that calling it repeatedly with the same instance does not cause issues. ( #176 , b/187443146 )

Версия 1.0.0-Alpha10

7 апреля 2021 г.

androidx.navigation:navigation-compose:1.0.0-alpha10 is released. Версия 1.0.0-Alpha10 содержит эти коммиты.

Изменения API

  • NavHost now accepts a Modifier , which is passed down to the composable container that wraps the destination composables. ( I85aca , b/175125483 )

Исправления ошибок

  • NavHost now works even when an OnBackPressedDispatcherOwner is not found, such is the case when previewing the NavHost . ( I7d8b4 )
  • Navigation Compose now depends on Navigation 2.3.5 , fixing an issue when using BackHandler inside a NavHost destination. ( I7e63b , b/182284739 )

Версия 1.0.0-Alpha09

10 марта 2021 г.

androidx.navigation:navigation-compose:1.0.0-alpha09 is released. Версия 1.0.0-Alpha09 содержит эти коммиты.

Изменения API

  • LocalViewModelStoreOwner.current now returns a nullable ViewModelStoreOwner to better determine whether a ViewModelStoreOwner is available in the current composition. APIs that require a ViewModelStoreOwner , such as viewModel() and NavHost , still throw an exception if a ViewModelStoreOwner is not set. ( Idf39a )

Исправления ошибок

  • Navigation Compose now depends on Navigation 2.3.4 which includes the fix for attempting to set the same ViewModelStore object after the graph has been set. ( I65c24 , b/177825470 )

Версия 1.0.0-альфа08

24 февраля 2021 года

androidx.navigation:navigation-compose:1.0.0-alpha08 is released. Версия 1.0.0-Alpha08 содержит эти коммиты.

Новые возможности

  • NavHost now populates the LocalSavedStateRegistryOwner CompositionLocal with that destination's NavBackStackEntry , ensuring that any state directly saved into the SavedStateRegistry will be saved and restored alongside the destination. ( I435d7 , b/179469431 )

Версия 1.0.0-альфа07

10 февраля 2021 г.

androidx.navigation:navigation-compose:1.0.0-alpha07 is released. Версия 1.0.0-Alpha07 содержит эти коммиты.

Обновления зависимости

Версия 1.0.0-альфа06

28 января 2021 г.

androidx.navigation:navigation-compose:1.0.0-alpha06 is released. Версия 1.0.0-Alpha06 содержит эти коммиты.

Изменения API

  • Added a getBackStackEntry(route: String) extension method on NavController that returns the associated NavBackStackEntry . ( If8931 )

Версия 1.0.0-альфа05

January 13, 2021

androidx.navigation:navigation-compose:1.0.0-alpha05 is released. Версия 1.0.0-Alpha05 содержит эти коммиты.

Updated to depend on Compose 1.0.0-alpha10.

Версия 1.0.0-альфа04

December 16, 2020

androidx.navigation:navigation-compose:1.0.0-alpha04 is released. Версия 1.0.0-Alpha04 содержит эти коммиты.

  • Updated for compatibility with Compose 1.0.0-alpha09 .

Версия 1.0.0-альфа03

December 2, 2020

androidx.navigation:navigation-compose:1.0.0-alpha03 is released. Версия 1.0.0-Alpha03 содержит эти коммиты.

Исправления ошибок

  • Fixed an issue where popBackStack() and navigateUp() would not work after a configuration change or process death and recreation. ( Icea47 , b/173281473 )
  • Navigating to a nested graph within your NavHost now works properly. ( I0948d , b/173647694 )

Версия 1.0.0-альфа02

11 ноября 2020 г.

androidx.navigation:navigation-compose:1.0.0-alpha02 is released. Версия 1.0.0-Alpha02 содержит эти коммиты.

Изменения API

  • Navigation compose now support NavOptions for using popUpTo and launchSingleTop operations ( If96c3 , b/171468994 )
  • Added a navigation function that takes a route instead of an ID that allows you to construct nested graphs in the Navigation Compose DSL. ( I1661d )
  • startDestination now comes before the route in the list of a parameters for a NavHost ( Ie620e )
  • You can now create a graph using the route as a start destination outside of a NavHost composable. ( Iceb75 )

Версия 1.0.0-альфа01

28 октября 2020 г.

android.navigation:navigation-compose:1.0.0-alpha01 is released. Версия 1.0.0-Alpha01 содержит эти коммиты.

Новые возможности

The navigation-compose artifact provides integration between the Navigation Component and Jetpack Compose . It uses @Composable functions as the destinations in your application.

This initial release provides:

  • A NavHost composable that allows you to construct your navigation graph via a Kotlin DSL.
  • Scoping of lifecycle, ViewModel , and remembered state at the destination level.
  • Automatic integration with the system back button.
  • Support for passing arguments, attaching deep links to destinations, and returning a result to previous destinations.
  • Compose specific helpers in rememberNavController() and currentBackStackEntryAsState() to allow hoisting state and connecting the NavController to composables outside of the NavHost (such as a bottom navigation bar).

See the Compose Navigation guide for more information.

Version 2.3.5

Version 2.3.5

7 апреля 2021 г.

androidx.navigation:navigation-*:2.3.5 is released. Version 2.3.5 contains these commits.

Новые возможности

  • When navigating using a NavDeepLinkRequest or Uri , you can now access the Uri , action, and mime type in the resulting destination by getting the intent from arguments via KEY_DEEP_LINK_INTENT , mirroring the functionality already available for external deep linking. ( I975c3 , b/181521877 )

Исправления ошибок

  • OnBackPressedCallbacks added to a dispatcher with the NavBackStackEntry as the LifecycleOwner now properly intercept back after the Activity Lifecycle is STOPPED , then STARTED ( Iff94f , b/182284739 )
  • Deep link domain parsing is now case insensitive, ensuring that www.example.com matches both www.example.com and www.Example.com . Note that query parameter names are still case sensitive. ( #144 , b/153829033 )
  • Fixed a NullPointerException that could occur when a destination has multiple non-nullable default arguments and you navigate to that destination while only overriding a subset of those arguments. ( aosp/1644827 )

Обновления зависимости

External Contribution

Version 2.3.4

Version 2.3.4

10 марта 2021 г.

androidx.navigation:navigation-*:2.3.4 is released. Version 2.3.4 contains these commits.

Новые возможности

  • ReferenceType arguments can now be properly parsed when sent as part of a deeplink URI. This supports both the raw integer value as well as hex values prefixed by 0x . ( #127 , b/179166693 )
  • The android:defaultValue for an argument with app:argType="float" now supports integer default values, allowing you to use android:defaultValue="0" rather than requiring the use of 0.0 . ( #117 , b/173766247 )

Исправления ошибок

  • Fix stuck installation progress when using Navigation's support for dynamic features. ( Ib27a7 , b/169636207 )
  • Calling setViewModelStore or setLifecycleOwner with the same object that has already been set will now be a no-op ( Idf491 , b/177825470 )
  • Safe-Args now adds suppress annotations on the proper methods when using java. ( I8fbc5 , b/179463137 )

External Contributions

  • Thanks JvmName for the pull request to ensure that ReferenceType arguments can now be properly parsed when sent as part of a deeplink URI. ( #127 , b/179166693 )
  • Thanks tatocaster for the pull request to allow the defaultValue for an argument with app:argType=”float” now supports integer default values. ( #117 , b/173766247 )

Version 2.3.3

Version 2.3.3

27 января 2021 г.

androidx.navigation:navigation-*:2.3.3 is released. Version 2.3.3 contains these commits.

Исправления ошибок

  • There is no longer a crash when popping a NavBackStackEntry before its Lifecycle is moved to CREATED . ( Ie3ba3 )
  • Fixed regression caused by b/171364502 where navigating to an activity with an animation resource value of 0 caused a ResourceNotFoundException . ( I7aedb , b/176819931 )

Version 2.3.2

Version 2.3.2

December 2, 2020

androidx.navigation:navigation-*:2.3.2 is released. Version 2.3.2 contains these commits.

Исправления ошибок

  • Fixed a regression in NavigationUI where using an <activity> destination with onNavDestinationSelected would fail to navigate to the Activity. ( I22e34 , b/171364502 )
  • Fixed an issue where navigation-dynamic-features-fragment would result in navigating to the newly installed destination multiple times. ( aosp/1486056 , b/169636207 )
  • Fixed an issue where default arguments would not be sent to OnDestinationChangedListener instances when using launchSingleTop . ( I2c5cb )
  • Fixed an issue where navigating to a nested navigation graph would not create a new graph instance on the back stack. ( Ifc831 )
  • Fixed an issue where using navigate() with a popUpTo that removed the last destination in a navigation graph would not immediately destroy and remove the navigation graph itself from the back stack. ( I910a3 )
  • Navigation SafeArgs now uses KotlinPoet version 1.7.2 which adds support for Kotlin's explicit API mode. ( I918b5 )
  • NavHostFragment.findNavController(Fragment) now also checks the root decor view of a DialogFragment in addition to the existing checks of the Fragment hierarchy and Fragment's view hierarchy. This allows you to test dialog fragments that use Navigation with FragmentScenario and Navigation.setViewNavController() . ( I69e0d )

Версия 2.3.1

Версия 2.3.1

14 октября 2020 г.

androidx.navigation:navigation-*:2.3.1 is released. Версия 2.3.1 содержит эти коммиты.

Новые возможности

  • Default Animator resources have been added to Navigation UI and are recommended over the default animation resources. ( b/167430145 )
  • NavOptions now overrides the hashcode and equals methods ( b/161586466 )
  • Navigation now includes the current destination in the “No destination with ID” IllegalArgumentException, which should improve the developer debugging experience. ( b/168311416 )

Исправления ошибок

  • Safe Args will no longer wrap the return line, even if the generated argument class name is longer than 100 characters. ( b/168584987 )

Dependency Changes

  • navigation-ui now depends on DrawerLayout 1.1.1 , ensuring that NavigationUI is able to open the drawer even when using LOCK_MODE_LOCKED_CLOSED or LOCK_MODE_LOCKED_OPEN . ( b/162253907 )
  • Safe Args now depends on KotlinPoet 1.6.0 ( aosp/1435911 )
  • Safe Args now depends on AGP 4.0.1 ( aosp/1442337 )

Версия 2.3.0

Версия 2.3.0

June 24, 2020

androidx.navigation:navigation-*:2.3.0 is released. Версия 2.3.0 содержит эти коммиты.

Major changes since 2.2.0

  • Feature Module integration : The navigation-dynamic-features-runtime and navigation-dynamic-features-fragment artifacts allow you to navigate to destinations that are defined in feature modules, automatically handling the installation of the feature modules as needed. See Navigate with feature modules for more information.
  • Navigation Testing : The navigation-testing artifact provides a TestNavHostController that allows you to set the current destination and verify the back stack after navigation operations. See Test Navigation for more information.
  • Returning a Result : The NavBackStackEntry associated with each destination on the Navigation back stack now allows you to access a SavedStateHandle suitable for storing small amounts of saved state that should be associated with a particular back stack entry. See Returning a result to the previous Destination for more information.
  • NavigationUI support for Openable : All usages of DrawerLayout in NavigationUI have been replaced with the more generic Openable interface added in CustomView 1.1.0 and implemented by DrawerLayout in DrawerLayout 1.1.0 .
  • Action and Mime Type support in deep links : Deep linking has been expanded to support app:action and app:mimeType in addition to the app:uri previously available. NavController now supports navigating by any combination of these fields via the new NavDeepLinkRequest class. See Navigate using NavDeepLinkRequest for more information.

Известные проблемы

  • Support for deep link actions and mime types is not yet available in Manifest Merger . Until that work is completed, any generated <intent-filter> elements from the <nav-graph> element in your manifest won't include your mime type in its <data> element or your custom <action> . You must manually add an appropriate <intent-filter> to your manifest.

Версия 2.3.0-rc01

June 10, 2020

androidx.navigation:navigation-*:2.3.0-rc01 is released. Версия 2.3.0-rc01 содержит эти коммиты.

Исправления ошибок

  • Fixed a NullPointerException when replacing an instance of a destination with no arguments with another instance with arguments with singleTop . ( b/158006669 )
  • All destination is unknown exceptions thrown by NavController now have additional debugging information to help determine the state of the NavController . ( b/157764916 )

Версия 2.3.0-бета01

20 мая 2020 г.

androidx.navigation:navigation-*:2.3.0-beta01 are released. Версия 2.3.0-beta01 содержит эти коммиты.

Исправления ошибок

  • Fixed an issue where the Lifecycle of the NavBackStackEntry would not be properly updated after process death. ( b/155218371 )
  • OnDestinationChangedListener instances registered before calling setGraph() are now properly sent the restored destination after a process death. ( b/155218371 )
  • When using singleTop , the NavBackStackEntry now correctly has its arguments updated and the updated arguments are sent to all OnDestinationChangeListener instances. ( b/156545508 )

Обновления зависимости

Version 2.3.0-alpha06

April 29, 2020

androidx.navigation:navigation-*:2.3.0-alpha06 is released. ( Version 2.3.0-alpha06 contains these commits. )

Новые возможности

  • Deep linking has been expanded to support app:action and app:mimeType in addition to the app:uri previously available. NavController now supports navigating by any combination of these fields via the new NavDeepLinkRequest class. ( b/136573074 , b/135334841 )

Изменения API

  • Greatly expanded the Kotlin DSL support for Dynamic Navigation destinations. ( b/148969800 )

Исправления ошибок

  • Fixed an issue where deep link Intents would be ignored when using a nested start destination. ( b/154532067 )

Версия 2.3.0-альфа05

15 апреля 2020 г.

androidx.navigation:navigation-*:2.3.0-alpha05 is released. Версия 2.3.0-alpha05 содержит эти коммиты.

Новые возможности

  • For dynamic graph includes using <include-dynamic> , you no longer need to specify app:graphPackage and a default one will be used by adding moduleName suffix to the applicationId after a dot. If you do need to customize your graphPackage , an ${applicationId} placeholder is now supported. ( b/152696768 )
  • The Navigation Graph Kotlin DSL now exposes a defaultArguments Map for actions, mirroring the ability to set default values on <action> elements in Navigation XML files. ( b/150345605 )

Исправления ошибок

  • From Navigation 2.2.2 : Fixed an IllegalStateException when deep linking to the start destination of your graph when you have multiple NavHostFragment instances in your Activity. ( b/147378752 )

Обновления зависимостей

Версия 2.3.0-альфа04

18 марта 2020 г.

androidx.navigation:navigation-*:2.3.0-alpha04 is released. Версия 2.3.0-alpha04 содержит эти коммиты.

Новые возможности

  • Added support for feature module activity and fragment destinations in the Navigation Kotlin DSL. ( b/148969800 )

Изменения API

  • The DynamicExtras class no longer uses a builder pattern and can now be constructed directly. ( aosp/1253671 )
  • DynamicActivityNavigator now takes a Context in its constructor rather than an Activity . ( aosp/1250252 )

Исправления ошибок

  • NavigationUI no longer ignores empty labels (ie, a destination with android:label=”” ) and now correctly sets the title to an empty string. ( b/148679860 )

Обновления зависимости

  • The Navigation Dynamic Features artifacts now depend on Play Core 1.6.5 . ( b/149556401 )

Версия 2.3.0-альфа03

March 4, 2020

androidx.navigation:navigation-*:2.3.0-alpha03 is released. Версия 2.3.0-alpha03 содержит эти коммиты.

Изменения API

Исправления ошибок

  • The navigation-common-ktx ProGuard rules now correctly only keep the NavArgs classes that are used rather than all NavArgs instances. ( b/150213558 )

Dependency changes

  • Navigation has reverted its dependency on Core 1.2.0 and now depends on Core 1.1.0 to avoid forcing developers to move to a newer dependency when Navigation does not depend on any new APIs in Core 1.2.0 .

Версия 2.3.0-альфа02

19 февраля 2020 г.

androidx.navigation:navigation-*:2.3.0-alpha02 is released. Версия 2.3.0-alpha02 содержит эти коммиты.

Новые возможности

  • The NavBackStackEntry now allows you to access a SavedStateHandle suitable for storing small amounts of saved state that should be associated with a particular back stack entry. See Returning a result for an example use case. ( b/79672220 )

Изменения API

  • Convenience methods of getCurrentBackStackEntry() and getPreviousBackStackEntry() have been added to make it easier to retrieve a NavBackStackEntry for the current and previous destinations. ( b/79672220 )

Исправления ошибок

  • navigateUp() now passes the current destination's arguments and the KEY_DEEP_LINK_INTENT to the previous destination when launching your app on your own task stack. ( b/147456890 )

Dependency changes

Версия 2.3.0-альфа01

5 февраля 2020 года

androidx.navigation:navigation-*:2.3.0-alpha01 is released. Version 2.3.0-alpha01 contains these commits .

Новые возможности

  • The new navigation-testing artifact provides a TestNavHostController class. This class provides an alternative to using a mock NavController when testing Navigation that allows you to set the current destination and verify the back stack after navigation operations. ( b/140884273 )
  • The new navigation-dynamic-features-fragment (and its transitive dependency, navigation-dynamic-features-runtime ) allows you to include destinations or entire navigation graphs (via <include-dynamic> ) from feature modules , providing seamless installation of on-demand feature modules when navigating to those destinations. See Navigate with feature modules for more information. ( b/132170186 )

Исправления ошибок

  • From Navigation 2.2.1 : Deep links without query parameters now correctly ignore any query parameters rather than appending them to trailing {argument} elements or not matching the deep link. ( b/147447512 )
  • From Navigation 2.2.1 : The navigation-ui ProGuard rules for DrawerArrowDrawable have been updated to ensure that android.enableJetifier=true is not required. ( b/147610424 )
  • From Navigation 2.2.1 : The navigation-common-ktx module now has a unique manifest package name instead of sharing the same manifest package name as navigation-runtime-ktx . ( aosp/1141947 )

Обновления зависимостей

Version 2.2.2

Version 2.2.2

15 апреля 2020 г.

androidx.navigation:navigation-*:2.2.2 are released. Version 2.2.2 contains these commits.

Исправления ошибок

  • Fixed an IllegalStateException when deep linking to the start destination of your graph when you have multiple NavHostFragment instances in your Activity. ( b/147378752 )
  • NavigationUI no longer ignores empty labels (ie, a destination with android:label=”” ) and now correctly sets the title to an empty string. This was previously released in Navigation 2.3.0-alpha04 . ( b/148679860 )
  • The navigation-common-ktx ProGuard rules now correctly only keep the NavArgs classes that are used rather than all NavArgs instances. This was previously released in Navigation 2.3.0-alpha03 . ( b/150213558

Обновления зависимостей

Версия 2.2.1

Версия 2.2.1

5 февраля 2020 года

androidx.navigation:navigation-*:2.2.1 is released. Version 2.2.1 contains these commits .

Исправления ошибок

  • Deep links without query parameters now correctly ignore any query parameters rather than appending them to trailing {argument} elements or not matching the deep link. ( b/147447512 )
  • The navigation-ui ProGuard rules for DrawerArrowDrawable have been updated to ensure that android.enableJetifier=true is not required. ( b/147610424 )
  • The navigation-common-ktx module now has a unique manifest package name instead of sharing the same manifest package name as navigation-runtime-ktx . ( aosp/1141947 )

Обновления зависимостей

Версия 2.2.0

Версия 2.2.0

22 января 2020 г.

androidx.navigation:navigation-*:2.2.0 is released. Version 2.2.0 contains these commits .

Важные изменения с версии 2.1.0

  • NavBackStackEntry : You can now call NavController.getBackStackEntry() , passing in the ID of a destination or navigation graph on the back stack. The returned NavBackStackEntry provides a Navigation-driven LifecycleOwner , ViewModelStoreOwner (the same returned by NavController.getViewModelStoreOwner() ), and SavedStateRegistryOwner , in addition to providing the arguments used to start that destination.
  • Lifecycle ViewModel SavedState Integration : SavedStateViewModelFactory is now the default factory used when using by navGraphViewModels() or the ViewModelProvider constructor with a ViewModelStoreOwner returned by NavController.getBackStackEntry() or NavController.getViewModelStoreOwner() .
  • Query Parameter Support for Deep Links : Deep links with query parameters now support reordered query parameters; arguments that have a default value or are nullable are now optional when matching deep links.
  • Improved Animation Support : NavHostFragment now uses FragmentContainerView from Fragment 1.2.0 , fixing animation z-ordering issues and window insets dispatching to Fragments.

Version 2.2.0-rc04

18 декабря 2019 г.

androidx.navigation:navigation-*:2.2.0-rc04 is released. Version 2.2.0-rc04 contains these commits .

Исправления ошибок

Version 2.2.0-rc03

4 декабря 2019 г.

androidx.navigation:navigation-*:2.2.0-rc03 is released. Version 2.2.0-rc03 contains these commits .

Исправления ошибок

  • Fixed an issue with deep link parsing when using query parameters and an argument as the last part of the path that prevented more than one character of the final path argument from being parsed. ( b/144554689 )
  • Fixed an issue with deep link parsing where optional parameters would receive "@null" instead of null . ( b/141613546 )
  • NavHostFragment now correctly restores the graph after a configuration change when used with FragmentContainerView . ( b/143752103 )

Dependency changes

  • Navigation now depends on Lifecycle 2.2.0-rc03 , Lifecycle ViewModel SavedState 1.0.0-rc03 , Activity 1.1.0-rc03 , and Fragment 1.2.0-rc03 where appropriate.

Version 2.2.0-rc02

7 ноября 2019 г.

androidx.navigation:navigation-*:2.2.0-rc02 is released. Version 2.2.0-rc02 contains these commits .

Dependency changes

  • Navigation now depends on androidx.lifecycle 2.2.0-rc02 .

Версия 2.2.0-rc01

23 октября 2019 года

androidx.navigation:navigation-*:2.2.0-rc01 is released with no changes since 2.2.0-beta01 . Version 2.2.0-rc01 contains these commits .

Версия 2.2.0-бета01

9 октября 2019 года

androidx.navigation:navigation-*:2.2.0-beta01 is released. Version 2.2.0-beta01 contains these commits .

Новые возможности

  • NavDestination and its subclasses now override toString() to provide more helpful information when debugging. ( b/141264986 )

Изменения в поведении

  • Extra query parameters are now ignored when matching deep links rather than causing the match to fail. ( b/141482822 )

Исправления ошибок

  • Fixed an issue where arguments in a deep link's path would be ignored if query parameters were also specified. ( b/141505755 )
  • The navArgs() Kotlin extension on Activity now has a better error message when there are no extras. ( b/141408999 )
  • Safe Args generated Directions Java classes now contain default values. ( b/141099045 )
  • Safe Args generated Args Java classes now contain default values. ( b/140123727 )
  • When using a Toolbar , NavigationUI no longer animates the text change when moving between two top level destinations. ( b/140848160 )

Version 2.2.0-alpha03

September 18, 2019

androidx.navigation:navigation-*:2.2.0-alpha03 is released. Version 2.2.0-alpha03 contains these commits .

Изменения в поведении

  • Calling setViewModelStore() after calling setGraph now results in an IllegalStateException . This should always be set by the NavHost as part of the initial setup to ensure that all NavBackStackEntry instances have a consistent storage for ViewModel instances. ( aosp/1111821 )

Исправления ошибок

  • Fixed a ConcurrentModificationException when using ViewModel instances attached to multiple different navigation graph scoped ViewModelStore instances. ( aosp/1112257 )

Версия 2.2.0-альфа02

September 5, 2019

androidx.navigation:navigation-*:2.2.0-alpha02 is released. The commits included in this version can be found here .

Новые возможности

  • Deep links with query parameters now support reordered query parameters; arguments that have a default value or are nullable are now optional when matching deep links. ( b/133273839 )
  • You can now call NavController.getBackStackEntry() , passing in the ID of a destination or navigation graph on the back stack. The returned NavBackStackEntry provides a Navigation-driven LifecycleOwner , ViewModelStoreOwner (the same returned by NavController.getViewModelStoreOwner() ), and SavedStateRegistryOwner , in addition to providing the arguments used to start that destination. ( aosp/1101691 , aosp/1101710 )

Исправления ошибок

  • Fixed an issue where adding a NavHostFragment to ViewPager2 failed with an IllegalArgumentException . ( b/133640271 )
  • NavInflater now avoids calling getResourceName() unnecessarily, speeding up inflation time by up to 40%. ( b/139213740 )

Версия 2.2.0-альфа01

August 7, 2019

androidx.navigation:navigation-*:2.2.0-alpha01 is released. The commits included in this version can be found here .

Новые возможности

  • SavedStateViewModelFactory is now the default factory used when using by navGraphViewModels() or the ViewModelProvider constructor with a ViewModelStoreOwner returned by NavController.getViewModelStoreOwner() . ( b/135716331 )

Изменения API

Исправления ошибок

  • NavHostFragment now uses FragmentContainerView , fixing animation z-ordering issues and window insets dispatching to Fragments. ( b/137310379 )

Версия 2.1.0

Версия 2.1.0

September 5, 2019

androidx.navigation:navigation-*:2.1.0 is released. The commits included in this version can be found here .

Important changes since 2.0.0

  • Scoping ViewModels to a navigation graph : You can now create ViewModels that are scoped at the navigation graph level using the by navGraphViewModels() property delegate for Kotlin users using the -ktx libraries or by using the getViewModelStoreOwner() API added to NavController . See Share UI-related data between destinations for more information.
  • Dialog destinations : You can now create <dialog> destinations that will show a DialogFragment when you navigate to them. NavHostFragment supports dialog destinations by default. See Create a destination from a DialogFragment for more information.
  • Navigating by Uri : You can now navigate using a Uri , which uses the <deepLink> you've added to a destination to navigate there. See Navigate using Uri for more information.
  • NavHostController : APIs used specifically for constructing a custom NavHost have been moved to NavHostController , allowing implementations to connect their NavController to the hosting LifecycleOwner , OnBackPressedDispatcher , and ViewModelStore .

Версия 2.1.0-rc01

August 7, 2019

androidx.navigation:navigation-*:2.1.0-rc01 is released. The commits included in this version can be found here .

Изменения API

  • The deprecated getViewModelStore() API on NavController introduced in 2.1.0-alpha02 has been removed. ( aosp/1091021 )

Version 2.1.0-beta02

July 19, 2019

androidx.navigation:*:2.1.0-beta02 is released. The commits included in this version can be found here .

Исправления ошибок

  • Removed unintentional jacoco dependency that was introduced in 2.1.0-beta01 . ( b/137782950 )

Версия 2.1.0-бета01

17 июля 2019 г.

androidx.navigation:*:2.1.0-beta01 is released. The commits included in this version can be found here .

Новые возможности

  • NavigationUI now animates the removal of the Up button when using setupWithNavController() with a Toolbar or CollapsingToolbarLayout . ( b/131403621 )

Исправления ошибок

  • Fixed a timing issue when using multiple NavHostFragments with the same container with findNavController() . ( b/136021571 )

Version 2.1.0-alpha06

2 июля 2019 г.

androidx.navigation:*:2.1.0-alpha06 is released. The commits included in this version can be found here .

Новые возможности

  • The app:navGraph attribute used by NavHostFragment has now been moved to the navigation-runtime artifact. Custom navigators that can be added via XML should use this attribute to gain integration with the Navigation Editor's Host panel. ( b/133880955 )

Изменения API

  • The getViewModelStore() API on NavController has been deprecated in favor of the new getViewModelStoreOwner() method that returns a ViewModelStoreOwner . ( aosp/987010 )
  • The implementation of floating window destinations, such as <dialog> destinations, has been generalized into a marker interface, FloatingWindow , that all <dialog> destinations now implement. NavigationUI methods for interacting with the top app bar now ignore FloatingWindow destinations. ( b/133600763 )

Изменения в поведении

  • Navigation now correctly keeps its state in sync with what is seen on the screen when using a <dialog> destination. As a consequence, Navigation now automatically pops <dialog> destinations when you navigate to a non-dialog and non-activity destination, such as a <fragment> destination. ( b/134089818 )

Исправления ошибок

  • Navigation now suppresses the animation that occurs when recreating the activity when handling a deep link, fixing a visual flash. ( b/130362979 )
  • Fixed a bug where the Navigation back stack would be out of sync when popping a Fragment as the initial fragment is being added. ( b/133832218 )

Version 2.1.0-alpha05

5 июня 2019 г.

androidx.navigation:*:2.1.0-alpha05 is released. The commits included in this version can be found here .

Изменения API

  • Host related APIs on NavController have been renamed and moved to a new subclass of NavController , NavHostController . ( aosp/966091 )
  • The NavController setHostOnBackPressedDispatcherOwner() method has been replaced with NavHostController 's setOnBackPressedDispatcher() method and now requires that you call setLifecycleOwner() prior to calling it. ( aosp/965409 )
  • NavHostController now contains a enableOnBackPressed(boolean) method that replaces the NavHostOnBackPressedManager class that was previously returned by setHostOnBackPressedDispatcherOwner() . ( aosp/966091 )

Исправления ошибок

  • Fixed an issue where the back stack was not correct after navigating by URI. ( b/132509387 )
  • Deep links automatically handled by NavController now only trigger once. ( b/132754763 )

Version 2.1.0-alpha04

16 мая 2019 г.

androidx.navigation:*:2.1.0-alpha04 is released. The commits included in this version can be found here .

Исправления ошибок

  • NavHostFragment correctly respects app:defaultNavHost when intercepting the system Back button events, fixing a regression in Navigation 2.1.0-alpha03 . b/132077777
  • DialogFragmentNavigator now correctly handles popBackStack() and navigateUp() operations. b/132576764
  • Fixed an IllegalStateException: unknown destination during restore issue when repeatedly navigating between nested graphs. b/131733658

Version 2.1.0-alpha03

7 мая 2019 г.

androidx.navigation:*:2.1.0-alpha03 is released. The commits included in this version can be found here .

Известные проблемы

  • NavHostFragment continues to intercept the system Back button despite using app:defaultNavHost="false" b/132077777

Новые возможности

  • You can now create <dialog> destinations that will show a DialogFragment when you navigate to them. NavHostFragment supports dialog destinations by default. b/80267254
  • In addition to calling navigate with a resource id or a NavDirections instance, you can now navigate via a Uri , which uses the <deepLink> you've added to a destination to navigate to the correct destination. b/110412864

Изменения в поведении

  • The default animations provided by NavigationUI have been sped up from 400ms to 220ms to match the default animation speed of activities and fragments. b/130055522

Изменения API

  • The createFragmentNavigator() method of NavHostFragment has been deprecated and its functionality moved to the new onCreateNavController() method to make it more clear that this is the correct entry point of adding custom Navigators when subclassing NavHostFragment . b/122802849
  • A hasDeepLink() method has been added to NavDestination to allow you to check if a given Uri can be handled by that destination or, in the case of a NavGraph , any destination in the navigation graph. b/117437718

Исправления ошибок

  • Default arguments are now correctly passed to OnDestinationChangedListener instances. b/130630686
  • NavHostFragment now intercepts system Back events using the OnBackPressedDispatcher , fixing an issue when doing conditional navigation in Fragment lifecycle methods upon returning to a Fragment. b/111598096
  • For Safe Args, an android:defaultValue=”@null” with an unspecified app:argType is now properly inferred as a string argument. b/129629192

Version 2.1.0-alpha02

April 3, 2019

androidx.navigation:*:2.1.0-alpha02 is released. The commits included in this version can be found here .

Новые возможности

  • You can now create ViewModels that are scoped at a navigation graph level via the by navGraphViewModels() property delegate for Kotlin users or by using the getViewModelStore() API added to NavController . b/111614463

Изменения API

  • You can now add an app:targetPackage to an <activity> destination to limit the matching package name. It supports app:targetPackage="${applicationId}" for restricting the package to your own application id. b/110975456

Исправления ошибок

  • The android:name for <activity> destinations is no longer parsed into a Class at inflation time, preventing ClassNotFoundExceptions when using dynamic features. b/124538597

Версия 2.1.0-альфа01

March 19, 2019

This is the first alpha release of Navigation 2.1.0 .

Dependency changes

  • Navigation now depends on androidx.core:core:1.0.1 and androidx.fragment:fragment:1.1.0-alpha05 . This release also removes the dependency on androidx.legacy:legacy-support-core-utils:1.0.0 . b/128632612

Изменения API

  • A new Navigation.createNavigateOnClickListener(NavDirections) method has been added as an alternative to creating a click listener with a resource ID and Bundle. b/127631752
  • FragmentNavigator.instantiateFragment is now deprecated. The default implementation now uses FragmentFactory to instantiate Fragments. b/119054429

Исправления ошибок

  • Navigation no longer sends a null Bundle when there are arguments attached to a destination, fixing an issue when using android:defaultValue="@null" . b/128531879
  • Safe Args now depends on KotlinPoet 1.1.0, fixing an issue with extremely long package names. b/123654948

Версия 2.0.0

Версия 2.0.0

14 марта 2019 года

Navigation 2.0.0 is released with no changes from 2.0.0-rc02 .

Version 2.0.0-rc02

March 6, 2019

Navigation 2.0.0-rc02 provides new artifacts with the androidx.navigation group ID and changes its dependencies to the AndroidX equivalents.

The behavior of 2.0.0-rc02 is identical to behavior to Navigation 1.0.0-rc02 and no changes to your code should be required to update from 1.0.0-rc02 besides updating your dependencies to match the new dependencies .

Your project must have migrated to AndroidX to use 2.X releases of Navigation. Navigation 1.0 stable will be the last release using the Support Library dependencies; all future development beyond 1.0 will be based on AndroidX and build upon the 2.0 stable release.

Pre-AndroidX Dependencies

For the pre-AndroidX versions of Navigation, include these dependencies:

dependencies {
    def nav_version = "1.0.0"

    implementation "android.arch.navigation:navigation-fragment:$nav_version" // For Kotlin use navigation-fragment-ktx
    implementation "android.arch.navigation:navigation-ui:$nav_version" // For Kotlin use navigation-ui-ktx
}

For Safe args , add the following classpath in your top level build.gradle file

buildscript {
    repositories {
        google()
    }
    dependencies {
        classpath "android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0"
    }
}

Версия 1.0.0

Версия 1.0.0

14 марта 2019 года

Navigation 1.0.0 is released with no changes from 1.0.0-rc02 .

Version 1.0.0-rc02

February 26, 2019

This is the second release candidate for Navigation's 1.0.0 stable release. This release contains a number of bug fixes.

Исправления ошибок

  • Fixed an issue where popBackStack() would be ignored if the root graph did not have an ID b/126251695
  • navigateUp() now correctly handles navigating back to your app's task when called after handling a deep link without FLAG_ACTIVITY_NEW_TASK b/126082008
  • Fixed an issue with ActivityNavigator.applyPopAnimationsToPendingTransition not applying the correct pop exit animation b/126237567
  • Kotlin code generated by Safe Args now properly escapes Kotlin keywords such as in and fun in the package name associated with the R class. b/126020455

Version 1.0.0-rc01

February 21, 2019

This is a release candidate for Navigation's 1.0.0 stable release. This release contains one bug fix.

Исправления ошибок

  • Fixed an issue when using Fragments and singleTop navigation operations b/124294805

Version 1.0.0-beta02

February 12, 2019

This release includes a number of minor improvements and important bug fixes.

Новые возможности

  • You can now use 0 as an android:defaultValue for reference arguments. b/124248602

Изменения в поведении

  • Exact deep link matches are now prioritized over deep links with .* or argument matches. b/123969518

Исправления ошибок

  • popBackStack() and navigateUp now correctly return false when popping the last destination on the back stack, fixing a regression introduced in 1.0.0-beta01 . b/123933201
  • Navigation now correctly sets the ClassLoader during restoration of saved instance state, avoiding issues when using custom classes in Navigator saved state or in arguments sent to a NavDestination . b/123893858
  • Safe Args generated NavArgs classes no longer crash when restoring a Parcelable[] argument from saved instance state. b/123963545
  • Safe Args now properly cleans up unnecessary generated Kotlin classes. b/124120883

Version 1.0.0-beta01

February 4, 2019

This is the first beta release of Navigation; moving forward, the Navigation API is expected to stay stable until the next version unless there is a critical problem. This release contains some bug fixes and behavior changes.

Изменения в поведении

  • Navigation now ensures that argument default values are treated identically at runtime and through Safe Args. As a consequence, only arguments with an app:argType="reference" can have a default value point to another resource (for example, @color/colorPrimary ). Attempting to use a reference default value with a different app:argType will result in an exception when parsing the navigation XML. b/123551990
  • Safe Args now depends on Android Gradle Plugin 3.3.0 aosp/888413
  • Safe Args now depends on Kotlin 1.3.20 aosp/888414

Исправления ошибок

  • Safe Args can now be used in library and feature modules on all versions of the Android Gradle Plugin. b/121304903
  • Fixed a regression that would cause a single popBackStack() operation to pop all copies of a destination off the top of the back stack, rather than just a single destination at a time. b/123552990
  • Fixed an issue where the FragmentNavigator state would desynchronize with the NavController 's state, causing an IllegalStateException when attempting to restore the back stack. b/123803044
  • Fixed an issue where the NavigationUI handled back arrow would not appear when using ProGuard with obfuscation. b/123449431
  • The code generated by Safe Args now properly handles using an app:argType pointing to a static inner class in the format .OuterClass$InnerClass . b/123736741
  • The Java code generated by Safe Args now properly handles global actions and deeply nested destinations. b/123347762

Версия 1.0.0-Альфа11

January 23, 2019

This is a hotfix release of 1.0.0-alpha10 that fixes an issue with Safe Args.

Исправления ошибок

  • Fixes an issue where Safe Args would fail to import the Directions class associated with global actions. b/123307342

Версия 1.0.0-Alpha10

January 23, 2019

Известные проблемы

  • Safe Args fails to import the Directions class associated with global actions. b/123307342

This release contains breaking API changes; please see the Breaking Changes section below.

Новые возможности

  • Kotlin users can now use the by navArgs() property delegate to lazily get a reference to a Safe Args generated NavArgs class in an Activity or Fragment . b/122603367
  • Safe Args now allows you to generate Kotlin code by applying the androidx.navigation.safeargs.kotlin plugin. The Kotlin code is built specifically for Kotlin only modules, using default arguments and immutable classes over the builder pattern that is still available via the previous androidx.navigation.safeargs plugin. b/110263087

Behavior Changes

  • Matching deep links are now biased towards the deep link that has the most matching arguments. b/118393029
  • Calling setGraph() on a NavController will now reset the back stack. b/111450672
  • Unknown deep links no longer throw an IllegalStateException , but are ignored, fixing issues with nested or multiple NavHostFragment s. b/121340440

Критические изменения

  • The NavOptions.applyPopAnimationsToPendingTransition() method for applying pop animations to an Activity has been moved to ActivityNavigator . b/122413117
  • Safe Args now avoids duplicating identical classes for actions without arguments. The return type for no argument methods in generated NavDirections classes is now NavDirections . b/123233147
  • Safe Args generated Directions classes no longer have a public constructor - you should only be interacting with the generated static methods. b/123031660
  • Safe Args generated NavDirections classes no longer have a public constructor - they should only be generated via the static methods in the generated Directions classes. b/122963206
  • The returned Bundle from NavDirections ' getArguments() is now marked as @NonNull rather than @Nullable . b/123243957

Исправления ошибок

  • NavDeepLinkBuilder now correctly handles multiple simultaneous PendingIntent s to the same destination by using the arguments you pass in to determine the uniqueness. b/120042732
  • NavController now correctly handles popBackStack() operations when using a nested NavHostFragment or other child Fragments with a back stack. b/122770335
  • NavigationUI now correctly sets the content description of the Up button. b/120395362
  • Safe Args generated Directions classes now correctly handle global actions that have the same id as an action on a destination. b/122962504
  • Safe Args generated NavDirections classes now correctly have equal hashCode() values when equals() would return true. b/123043662
  • FragmentNavigator now throws a better error message if you attempt to do custom FragmentTransactions on the NavHostFragment 's FragmentManager . You should always use getChildFragmentManager() . b/112927148

Версия 1.0.0-Alpha09

December 18, 2018

This release contains breaking API changes; please see the Breaking Changes section below.

We have chosen not to continue development of the android.arch.navigation:navigation-testing artifact. While it has proven helpful for internal testing of NavController , we strongly recommend alternate testing strategies, such as mocking the NavController instance in order to verify that the correct navigate() calls are being done. This approach is discussed in detail in the Single Activity talk at AndroidDevSummit 2018 and we'll be working on additional documentation specifically around testing with Navigation.

Новые возможности

  • MenuItem s with menuCategory="secondary" will no longer pop the back stack when used with NavigationUI methods. b/120104424
  • AppBarConfiguration now allows you to set a fallback OnNavigateUpListener instance which will be called when navController.navigateUp() returns false . b/79993862 b/120690961

Критические изменения

  • When using an <argument> with an argType="reference" , Navigation no longer parses the reference, instead providing the raw resource ID itself. b/111736515
  • onNavDestinationSelected() now pops back to the start destination of your navigation graph by default, making them consistent with the setup methods. Add menuCategory="secondary" to your MenuItem to avoid popping the back stack. aosp/852869
  • The fromBundle() methods of generated Args classes now take a non-null Bundle instead of a nullable Bundle aosp/845616

Исправления ошибок

  • Arguments are now properly parsed from deep links as the correct argType instead of always as strings b/110273284
  • Navigation now correctly exports its public resources b/121059552
  • Safe Args is now compatible with Android Gradle Plugin 3.4 Canary 4 and higher b/119662045

Версия 1.0.0-альфа08

December 6, 2018

This release contains breaking API changes; please see the Breaking Changes section below.

Новые возможности

  • Destination labels, when used with NavigationUI methods, will now automatically replace {argName} instances in your android:label with the correct argument b/80267266
  • Navigation now depends on Support Library 28.0.0 b/120293333

Критические изменения

  • OnNavigatedListener has been renamed to OnDestinationChangedListener b/118670572
  • OnDestinationChangedListener now also passes the Bundle of arguments aosp/837142
  • The app:clearTask and app:launchDocument attributes and their associated methods have been removed. Use app:popUpTo with the root of your graph to remove all destinations from your back stack. b/119628354
  • ActivityNavigator.Extras now uses a Builder pattern and adds the ability to set any Intent.FLAG_ACTIVITY_ flags aosp/828140
  • NavController.onHandleDeepLink has been renamed to handleDeepLink aosp/836063
  • Many classes and methods not meant for subclassing, such as NavOptions , NavInflater , NavDeepLinkBuilder , and AppBarConfiguration , have been made final aosp/835681
  • The deprecated NavHostFragment.setGraph() method has been removed aosp/835684
  • The deprecated NavigationUI.navigateUp(DrawerLayout, NavController) method has been removed. aosp/835684
  • Fragment creation has been moved to FragmentNavigator , making it easier to delegate Fragment creation to a FragmentFactory . b/119054429
  • The constructor for NavGraphNavigator no longer takes a Context aosp/835340
  • NavigatorProvider is now a class, rather than an interface. The NavigatorProvider returned by getNavigatorProvider() has not changed its functionality. aosp/830660
  • NavDestination.navigate() has been removed. Call navigate() on the Navigator instead. aosp/830663
  • Significant refactoring of Navigator , removing the need for OnNavigatorNavigatedListener and instead having navigate return the NavDestination that was navigated to.
  • Navigator instances can no longer send pop events to the NavController . Consider using a OnBackPressedCallback to intercept back button presses and call navController.popBackStack() . aosp/833716

Исправления ошибок

  • popUpTo now works consistently when the destination is a <navigation> element b/116831650
  • Fixed a number of bugs that resulted in an IllegalArgumentException when using nested graphs b/118713731 b/113611083 b/113346925 b/113305559
  • The dataPattern attribute of <activity> destinations will now populate arguments from non-String arguments by calling toString() b/120161365

Safe Args

  • Safe Args supports Serializable objects, including Enum values. Enum types can set a default value by using the enum literal without the class name (eg app:defaultValue="READ" ) b/111316353
  • Safe Args supports arrays of all supported types b/111487504
  • Safe Args now ignores subfolders of resource directories b/117893516
  • Safe Args adds @Override annotations where appropriate b/117145301

Версия 1.0.0-альфа07

October 29, 2018

Новые возможности

Критические изменения

  • The navigation-testing-ktx module has been folded into the navigation-testing artifact and will no longer be published.
  • The navigation-testing artifact now has a dependency on the Kotlin standard library. The API has been changed to be more consistent with Kotlin conventions, but you can continue to use it for tests written in Java.
  • Metadata manifest registered navigation graphs are no longer supported. b/118355937
  • Actions can no longer be attached to <activity> destinations. aosp/785539

Исправления ошибок

  • Deep links now correctly parse query parameters. b/110057514
  • Activity destinations now correctly apply all enter and exit animations. b/117145284
  • Fixed crash that occurs after configuration changes when using custom Navigators. b/110763345

Safe Args

  • Safe args now have a fixed dependency on Android Gradle Plugin 3.2.1. b/113167627
  • Directions can now be generated for inner classes. b/117407555
  • Fixed an issue with generating Directions to an <include> graph. b/116542123

Версия 1.0.0-альфа06

September 20, 2018

Новые возможности

Изменения API

  • Breaking Change: The Navigator navigate() method now takes a Navigator.Extras parameter.
  • NavController's getGraph() method is now NonNull b/112243286

Исправления ошибок

  • NavigationUI.setupWithNavController() no longer leaks views if used with views from individual destinations b/111961977
  • Navigator onSaveState() is now only called once b/112627079

Safe Args

  • Navigation destination Directions classes now extend their parent's Directions class if it exists b/79871405
  • Directions and Args classes now have a useful toString() implementation b/111843389

Версия 1.0.0-альфа05

August 10, 2018

Исправления ошибок

  • Fix a bug which cause incorrect backstack behavior. b/111907708
  • Fix a bug in equals() of Generated Args classes. b/111450897
  • Fix a build failure in Safe Args. b/109409713
  • Fix a conversion from resource identifiers to java names b/111602491
  • Fix error messages about nullability in Safe Args plugin.
  • Add missing nullability annotations.

Версия 1.0.0-альфа04

July 19, 2018

Navigation 1.0.0-alpha04 and the associated Safe Args gradle plugin contains a number of API changes, behavior changes, and bug fixes.

API / Behavior Changes

  • NavHostFragment will always set the current Fragment as the primary navigation fragment, ensuring that child fragment managers are popped before the outer NavController is popped b/111345778

Safe Args

  • Breaking Change: app:type has been changed to app:argType to avoid conflicts with other libraries such as ConstraintLayout 2.0.0-alpha1 b/111110548
  • Error messages from Safe Args are now clickable b/111534438
  • Args classes now confirms that NonNull attributes are actually not null b/111451769
  • Additional NonNull annotations have been added to NavDirections and Args generated classes b/111455455 b/111455456

Исправления ошибок

  • Fixed an issue with the system back button after deep linking to a fragment destination b/111515685

Версия 1.0.0-альфа03

July 12, 2018

Navigation 1.0.0-alpha03 and the associated Safe Args gradle plugin contains a number of API changes, behavior changes, and bug fixes.

API / Behavior Changes

  • A NavigationUI.setupWithNavController method for Toolbar has been added b/109868820
  • A NavigationUI.setupWithNavController method for CollapsingToolbarLayout has been added b/110887183
  • popBackStack() now returns false when the back stack is empty or when the given destination ID is not in the back stack b/110893637
  • FragmentNavigator now ignores navigation operations after FragmentManager has saved state, avoiding “Can not perform this action after onSaveInstanceState” exceptions b/110987825

Safe Args

  • Breaking Change: Non-alphanumeric characters in action and argument names will be replaced by camel casing in the respective NavDirections method names
    • Eg DemoController.index will become setDemoControllerIndex b/79995048
    • Eg action_show_settings will become actionShowSettings b/79642240
  • Breaking Change: Arguments are now considered non-null by default. To allow null values on string and parcelable arguments, add app:nullable="true" b/79642307
  • You can now use app:type="long" with defaultValues in the form of “123L” b/79563966
  • Parcelable arguments are now supported, using a fully qualified class name for app:type . The only default value supported is "@null" b/79563966
  • Args classes now implement equals() and hashCode() b/79642246
  • The Safe Args plugin can now be applied to library projects b/80036553
  • The Safe Args plugin can now be applied to feature projects b/110011752

Исправления ошибок

  • Fixed issues when navigating during Fragment lifecycle methods b/109916080
  • Fixed issues when navigating through nested graphs multiple times b/110178671
  • Fixed issues when using setPopUpTo with the first destination in the graph b/109909461
  • Fixed issue where all app:defaultValue values were being passed as Strings b/110710788
  • aapt2 bundled with Android Gradle Plugin 3.2 Beta 01 now adds keep rules for every android:name attribute in Navigation XML files b/79874119
  • Fixed memory leak when replacing the default FragmentNavigator b/110900142

Версия 1.0.0-альфа02

June 7, 2018

Behavior Changes

  • FragmentNavigator now uses setReorderingAllowed(true) . b/109826220

  • Navigation now URLDecodes arguments parsed from deep links URLs. b/79982454

Исправления ошибок

  • Fixed an IllegalStateException when calling navigate from Fragment lifecycle methods. b/79632233

  • Navigation now depends on Support Library 27.1.1 to fix flickering when using animations. b/80160903

  • Fixed an IllegalArgumentException when using defaultNavHost="true" as a child fragment. b/79656847

  • Fixed a StackOverflowError when using NavDeepLinkBuilder. b/109653065

  • Fixed an IllegalArgumentException when navigating back to a nested graph. b/80453447

  • Fixed an issue with overlapping Fragments when using launchSingleTop . b/79407969

  • Navigation now builds the correct synthetic back stack for nested graphs. b/79734195

  • NavigationUI will now highlight the correct item when using a nested graph as a MenuItem . b/109675998

Изменения API

  • The clearTask attribute for actions and the associated API in NavOptions has been deprecated. b/80338878

  • The launchDocument attribute for actions and the associated API in NavOptions has been deprecated. b/109806636

Версия 1.0.0-альфа01

8 мая 2018 г.

Navigation provides a framework for building in-app navigation. This initial release is 1.0.0-alpha01 .

,

Навигация

Navigation is a framework for navigating between 'destinations' within an Android application that provides a consistent API whether destinations are implemented as Fragments, Activities, or other components.
Последнее обновление Стабильный выпуск Кандидат на выпуск Бета-версия Альфа-релиз
12 марта 2025 г. 2.8.9 - - 2.9.0-alpha08

Объявление зависимостей

To add a dependency on Navigation, you must add the Google Maven repository to your project. Для получения дополнительной информации прочтите репозиторий Google Maven .

Добавьте зависимости для нужных вам артефактов в файл build.gradle для вашего приложения или модуля:

Groovy

plugins {
  // Kotlin serialization plugin for type safe routes and navigation arguments
  id 'org.jetbrains.kotlin.plugin.serialization' version '2.0.21'
}
  
dependencies {
  def nav_version = "2.8.9"

  // Jetpack Compose Integration
  implementation "androidx.navigation:navigation-compose:$nav_version"

  // Views/Fragments Integration
  implementation "androidx.navigation:navigation-fragment:$nav_version"
  implementation "androidx.navigation:navigation-ui:$nav_version"

  // Feature module support for Fragments
  implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

  // Testing Navigation
  androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"

  // JSON serialization library, works with the Kotlin serialization plugin.
  implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3"
}

Kotlin

plugins {
  // Kotlin serialization plugin for type safe routes and navigation arguments
  kotlin("plugin.serialization") version "2.0.21"
}

dependencies {
  val nav_version = "2.8.9"

  // Jetpack Compose integration
  implementation("androidx.navigation:navigation-compose:$nav_version")

  // Views/Fragments integration
  implementation("androidx.navigation:navigation-fragment:$nav_version")
  implementation("androidx.navigation:navigation-ui:$nav_version")

  // Feature module support for Fragments
  implementation("androidx.navigation:navigation-dynamic-features-fragment:$nav_version")

  // Testing Navigation
  androidTestImplementation("androidx.navigation:navigation-testing:$nav_version")

  // JSON serialization library, works with the Kotlin serialization plugin
  implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
}

Safe Args

Чтобы добавить Safe Args в свой проект, включите следующий classpath в файл build.gradle верхнего уровня:

классный

buildscript {
    repositories {
        google()
    }
    dependencies {
        def nav_version = "2.8.9"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }
}

Котлин

buildscript {
    repositories {
        google()
    }
    dependencies {
        val nav_version = "2.8.9"
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")
    }
}

Вам также необходимо применить один из двух доступных плагинов.

Чтобы сгенерировать код языка Java, подходящий для Java или смешанных модулей Java и Kotlin, добавьте эту строку в файл build.gradle вашего приложения или модуля :

классный

plugins {
  id 'androidx.navigation.safeargs'
}

Котлин

plugins {
    id("androidx.navigation.safeargs")
}

В качестве альтернативы, чтобы сгенерировать код Kotlin, подходящий для модулей только Kotlin, добавьте:

классный

plugins {
  id 'androidx.navigation.safeargs.kotlin'
}

Котлин

plugins {
    id("androidx.navigation.safeargs.kotlin")
}

У вас должно быть android.useAndroidX=true в файле gradle.properties в соответствии с переходом на AndroidX .

For information on using Kotlin extensions, see the ktx documentation .

For more information about dependencies, see Add Build Dependencies .

Обратная связь

Ваши отзывы помогают сделать Jetpack лучше. Дайте нам знать, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете добавить свой голос к существующей проблеме, нажав кнопку со звездочкой.

Создать новую задачу

Дополнительную информацию см. в документации по системе отслеживания проблем .

Version 2.9

Version 2.9.0-alpha08

12 марта 2025 г.

androidx.navigation:navigation-*:2.9.0-alpha08 is released. Version 2.9.0-alpha08 contains these commits .

Исправления ошибок

  • From Navigation 2.8.9 : Fixed a regression found in Navigation 2.8.8 that required a deep link to match all of the fields of a deep link request or intent exactly in order to be considered a match. This caused deep links that contained partial field matches and did not have others to no longer work. ( Ie5e36 , b/399826566 )

External Contribution

  • New common parser function to create a NavUri . Thanks Konstantin Tskhovrebov! ( If0a6a )

Version 2.9.0-alpha07

26 февраля 2025 г.

androidx.navigation:navigation-*:2.9.0-alpha07 is released. Version 2.9.0-alpha07 contains these commits .

Исправления ошибок

  • Fixed an issue where attempting to saveState with non-inclusive pop would result in a null savedState that could cause a crash on restoration. ( I9f3e8 , b/395091644 )
  • From Navigation 2.8.8 : NavDeepLink matching has been fixed where a deeplink and a deeplink request have to match exactly on uri, action, and mime. Matching is no longer allowed if only one or two fields match. ( I3b029 , b/395712033 )
  • From Navigation 2.8.8 : Fixed a bug where routes with wildcard paths do not match with an added deeplink ( I7ea92 , b/389970341 )

External Contribution

  • Extract a navigation-common, navigation-runtime, and navigation-compose APIs to the common platform. Thanks Konstantin Tskhovrebov! ( I1e626 , Ica76f , Idf479 )

Известные проблемы

  • Due to the work to address b/395712033 , deeplinks are incorrectly required to have all of the same fields as the deeplink request and/or the Intent . Deeplinks должны потребоваться только для соответствия областям, которые у них есть, и не включенные поля следует игнорировать. This has been fixed for a later release as part of b/399826566 .

Version 2.9.0-alpha06

12 февраля 2025 г.

androidx.navigation:navigation-*:2.9.0-alpha06 is released. Version 2.9.0-alpha06 contains these commits .

Новые возможности

  • Navigation Safe Args actions are now generated with the @CheckResult annotation to ensure they are used. ( I14d4c , b/356323084 )

Исправления ошибок

  • Fixed an error in NavController where the backStack states were incorrectly attempted to be restored into an array when they were saved into a list. ( Idfb9b )
  • From Navigation 2.8.7 : Navigation Safe Args now provides support for composable destinations. ( I35320 , b/362791955 )

Version 2.9.0-alpha05

29 января 2025 г.

androidx.navigation:navigation-*:2.9.0-alpha05 is released. Version 2.9.0-alpha05 contains these commits .

Исправления ошибок

  • Fix an issue that caused an unexpected scale animation when using Navigation Compose. ( I480f4 , b/353294030 )
  • From Navigation 2.8.6 : NavDestination labels provided through XML will be parsed via NavType.get to ensure custom NavType logic is respected. ( I7ec2f , b/388100796 )
  • From Navigation 2.8.6 : When navigating to activity with dataPattern , ActivityNavigator will now try to encode the arg value with the argument's NavType . ( I16376 , b/383616432 )
  • From Navigation 2.8.5 : Fixed an issue that caused an unexpected scale animation when using Navigation Compose and calling navigate in the same frame that the current animation is ending. ( I26cb1 , b/353294030 )

Version 2.9.0-alpha04

11 декабря 2024 г.

androidx.navigation:navigation-*:2.9.0-alpha04 is released. Version 2.9.0-alpha04 contains these commits .

Новые возможности

The table below provides the reified and KClass APIs.

материализованный KClass
composable<TestClass> { } composable(TestClass::class) { }
navigation<NestedGraph>(startDestination = TestClass::class) navigation(route = NestedGraph::class, startDestination = TestClass::class)
dialog<TestClass> {} dialog(TestClass::class) {}
navDeepLink<TestClass>(baseUri) navDeepLink(TestClass::class, baseUri)
NavDeepLink.Builder.setUriPattern<TestClass>(baseUri) NavDeepLink.Builder.setUriPattern(TestClass::class, baseUri)
NavDestinationBuilder.deepLink<TestDeepLink>(baseUri) { } NavDestinationBuilder.deepLink(TestDeepLink::class, baseUri) { }
navController.getBackStackEntry<TestClass>() navController.getBackStackEntry(TestClass::class)
navController.popBackStack<TestClass>(true) navController.popBackStack(TestClass::class, true)
navController.clearBackStack<TestClass>() navController.clearBackStack(TestClass::class)
NavOptions.setPopUpTo<TestClass>() NavOptions.setPopUpTo(TestClass::class)
navOptions { popUpTo<TestClass> {...} } navOptions { popUpTo(TestClass::class) {...} }
NavGraph.setStartDestination<TestClass>() NavGraph.setStartDestination(TestClass::class)
NavGraph.findNode<TestClass>() NavGraph.findNode(TestClass::class)
backStackEntry.toRoute<TestClass>() backStackEntry.toRoute(TestClass::class)
savedStateHandle.toRoute<TestClass>() savedStateHandle.toRoute(TestClass::class)

Изменения API

  • The kotlin-specific NavGraph.setStartDestination overload for type safety is hidden from Java sources. ( Ic640c , b/364634035 )

Исправления ошибок

  • From Navigation 2.8.5 : Fixed an issue where NavHost could throw an exception inside of the PredictiveBackHandler if the back stack is popped down to 1 entry and a system back are triggered in the same frame. ( I1a429 , b/375343407 )
  • From Navigation 2.8.5 : Fixed NavDestination NullPointerException when updating a graph's startDestination . ( I99421 , b/361560785 )

External Contribution

Version 2.9.0-alpha03

13 ноября 2024 г.

androidx.navigation:navigation-*:2.9.0-alpha03 is released. Version 2.9.0-alpha03 contains these commits .

Новые возможности

  • Navigation type safety now supports value classes as a route or as the argument type of a route. ( I9344a , b/374347483 )

Исправления ошибок

  • Fixed a ConcurrentModificationException that could occur when a LifecycleObserver attached to a NavBackStackEntry triggers a change to the back stack when the host LifecycleOwner such as the containing Activity or Fragment changes its lifecycle state. ( Ia9494 )

Version 2.9.0-alpha02

30 октября 2024 г.

androidx.navigation:navigation-*:2.9.0-alpha02 is released. Version 2.9.0-alpha02 contains these commits .

External Contribution

  • New common NavController.handleDeepLink(request: NavDeepLinkRequest) method. Thanks Konstantin Tskhovrebov! ( I3e228 )

Version 2.9.0-alpha01

16 октября 2024 г.

androidx.navigation:navigation-*:2.9.0-alpha01 is released. Version 2.9.0-alpha01 contains these commits .

Новые возможности

  • Custom Navigators can now mark their destinations as implementing the SupportingPane interface which indicates to the NavController that these destinations will be shown alongside other destinations. By using this interface, multiple destinations can be RESUMED at the same time, for instance. ( Id5559 )
  • From Navigation 2.8.3 : Added new lint checks for the navigation-common , navigation-runtime , and navigation-compose modules to help identify any type-safe routes that are not correctly annotated with @Serializable . This check is applied to all NavGraphBuilder and NavDeepLinkBuilder extension functions. ( I4a259 , I95402 , Ie601a , Id8c6e , I28bda , b/362725816 )
  • From Navigation 2.8.3 : Added new lint checks for the navigation-common , navigation-runtime , and navigation-compose modules to help identify any type-safe routes with Enum arguments that are not correctly annotated with @Keep . This check is applied to all NavGraphBuilder and NavDeepLinkBuilder extension functions. ( I4a259 , I95402 , Ie601a , Id8c6e , I2b46f , b/358687142 )

Behavior Changes

  • Attempting to use a NavController that has been previously DESTROYED will now cause an IllegalStateException . ( I520da , b/369616172 )

Исправления ошибок

  • Update Enum class not found exception to suggest using @Keep annotation in case the Enum class gets erased in minified builds. ( I90e79 , b/358137294 )

Известные проблемы

  • There is an issue with the new lint rules that were added in Navigation 2.8.* that cause an Obsolete custom lint check error when attempting to run lint with Android Gradle Plugin 8.4+. ( b/368070326 , b/371463741 )

Version 2.8

Version 2.8.9

12 марта 2025 г.

androidx.navigation:navigation-*:2.8.9 is released. Version 2.8.9 contains these commits .

Исправления ошибок

  • Fixed a regression found in Navigation 2.8.8 that required a deep link to match all of the fields of a deep link request or intent exactly in order to be considered a match. This caused deep links that contained partial field matches and did not have others to no longer work. ( Ie5e36 , b/399826566 )

Version 2.8.8

26 февраля 2025 г.

androidx.navigation:navigation-*:2.8.8 is released. Version 2.8.8 contains these commits .

Исправления ошибок

  • Fixed a bug where routes with wildcard paths do not match with an added deeplink. ( I7ea92 , b/389970341 )
  • NavDeepLink matching has been fixed where a deeplink and a deeplink request have to match exactly on uri, action, and mime. Matching is no longer allowed if only one or two fields match. ( I3227f , b/395712033 )

Известные проблемы

  • Due to the work to address b/395712033 , deeplinks are incorrectly required to have all of the same fields as the deeplink request and/or the Intent . Deeplinks должны потребоваться только для соответствия областям, которые у них есть, и не включенные поля следует игнорировать. This has been fixed for a later release as part of b/399826566 .

Version 2.8.7

12 февраля 2025 г.

androidx.navigation:navigation-*:2.8.7 is released. Version 2.8.7 contains these commits .

Исправления ошибок

  • Navigation Safe Args now provides support for composable destinations. ( I35320 , b/362791955 )

Version 2.8.6

29 января 2025 г.

androidx.navigation:navigation-*:2.8.6 is released. Version 2.8.6 contains these commits .

Исправления ошибок

  • NavDestination labels provided through XML will be parsed via NavType.get to ensure custom NavType logic is respected. ( Id366d , b/388100796 )
  • When navigating to activity with dataPattern , ActivityNavigator will now try to encode the arg value with the argument's NavType . ( I1a71d , b/383616432 )

Version 2.8.5

11 декабря 2024 г.

androidx.navigation:navigation-*:2.8.5 is released. Version 2.8.5 contains these commits .

Исправления ошибок

  • Fixed an issue where NavHost could throw an exception inside of the PredictiveBackHandler if the back stack is popped down to 1 entry and a system back are triggered in the same frame. ( I1a429 , b/375343407 )
  • Fixed NavDestination NullPointerException when updating a graph's startDestination . ( I99421 , b/361560785 )
  • Fixed an issue that caused an unexpected scale animation when using Navigation Compose and calling navigate in the same frame that the current animation is ending. ( I26cb1 , b/353294030 )
  • Fixed a ConcurrentModificationException that could occur when a LifecycleObserver attached to a NavBackStackEntry triggers a change to the back stack when the host LifecycleOwner such as the containing Activity or Fragment changes its lifecycle state. ( Ia9494 )

External Contribution

  • Navigation type safety now supports List<Enum> as an argument type of a route without requiring any custom NavType . Thanks Csaba Kozák ! ( GH-725 , b/375559962 )

Version 2.8.4

13 ноября 2024 г.

androidx.navigation:navigation-*:2.8.4 is released. Version 2.8.4 contains these commits .

Новые возможности

Исправления ошибок

Version 2.8.3

16 октября 2024 г.

androidx.navigation:navigation-*:2.8.3 is released. Version 2.8.3 contains these commits .

Новые возможности

  • Added new lint checks for the navigation-common , navigation-runtime , and navigation-compose modules to help identify any type-safe routes that are not correctly annotated with @Serializable . This check is applied to all NavGraphBuilder and NavDeepLinkBuilder extension functions. ( I4a259 , I95402 , Ie601a , Id8c6e , I28bda , b/362725816 )
  • Added new lint checks for the navigation-common , navigation-runtime , and navigation-compose modules to help identify any type-safe routes with Enum arguments that are not correctly annotated with @Keep . This check is applied to all NavGraphBuilder and NavDeepLinkBuilder extension functions. ( I4a259 , I95402 , Ie601a , Id8c6e , I2b46f , b/358687142 )

Исправления ошибок

  • Fixed an issue where the new lint rules that were added in Navigation 2.8.* would cause an Obsolete custom lint check error when attempting to run lint with Android Gradle Plugin 8.4+. ( I1be3d , b/368070326 , b/371463741 )

Известные проблемы

  • Navigation lint will throw an Obsolete custom lint check error when attempting to run lint with Lint 16 (AGP 8.7) or higher. ( b/371926651 )

Version 2.8.2

2 октября 2024 г.

androidx.navigation:navigation-*:2.8.2 is released. Version 2.8.2 contains these commits .

Новые возможности

  • Navigation Type Safety now supports Serializable classes that include a Double , Double? , DoubleArray , DoubleArray? , List<Double> , and List<Double>? without requiring any custom NavType . ( I570eb , Ibc4c0 , I37461 , I5bed4 , b/359245753 )

Исправления ошибок

  • Improved the error message for when Navigation fails to map a route's argument to a NavType , the new error message will contain the argument name, argument fully qualified name, and the route's fully qualified name. ( Id8416 , b/346264232 )

Version 2.8.1

18 сентября 2024 г.

androidx.navigation:navigation-*:2.8.1 is released. Version 2.8.1 contains these commits .

Новые возможности

  • Added a new lint rule to ensure the use of the popBackStack function that takes a reified class type when attempting to popBackStack using type-safe APIs. ( Ief161 , b/358095343 )

Исправления ошибок

  • Navigation now requires that the route passed to a NavGraph 's startDestination contains the values for all required arguments, which includes arguments that are non-nullable and have no default value. ( I18e74 , b/362594265 )
  • Navigation safe args has added support for non-nullable strings such that "null" values will be parsed and stored into the bundle as is. This departs from existing behavior where "null" values are parsed into a null object. This change only applies to non-nullable String types. Nullable strings remain unchanged. ( I08b4a , b/348936238 )
  • A NavDestination can no longer be deeplinked into except through a deep link that was explicitly added to the destination. This also means that you can only navigate to a destination's route with the navigate function overload that takes a string route. This fixes a vulnerability that made it possible to deep link to a potentially protected destination. ( Ie30e6 )

Dependency Update

  • Navigation Safe Args now depends on Kotlin 1.9.24, rather than Kotlin 2.X, ensuring that developers are not forced to update. ( a4129a )
  • Navigation Compose now depends on Compose 1.7.2 .

Version 2.8.0

4 сентября 2024 г.

androidx.navigation:navigation-*:2.8.0 is released. Version 2.8.0 contains these commits .

Important changes since 2.7.0

Navigation Kotlin DSL Type-Safety

  • Navigation now provides type-safety for the Kotlin DSL (used by Navigation Compose) using Kotlin Serialization to allow you to define destinations in your navigation graph via type safe objects and data classes:
    // Define a home destination that doesn't take any arguments
    @Serializable
    object Home

    // Define a profile destination that takes an ID
    @Serializable
    data class Profile(val id: String)

    // Now define your NavHost using type safe objects
    NavHost(navController, startDestination = Home) {
        composable<Home> {
            HomeScreen(onNavigateToProfile = { id ->
                navController.navigate(Profile(id))
            })
        }
        composable<Profile> { backStackEntry ->
            val profile: Profile = backStackEntry.toRoute()
            ProfileScreen(profile)
        }
    }

See the Navigation Compose meet Type Safety blog post for more information.

Navigation Compose Predictive Back

  • Navigation Compose now provides support for Predictive in-app back via the new SeekableTransitionState APIs from compose-animation. This allows you to use the back gesture to see the previous destination with your custom Transition before deciding to either commit the transaction via the completed gesture or cancel.

Navigation Fragment Composable

  • Added a new navigation-fragment-compose artifact that includes a ComposableNavHostFragment alternative to NavHostFragment that allows you to add composable destinations to your Navigation XML files. Each composable destination must be expressed as a top-level, no argument @Composable method whose fully qualified name is used as the android:name attribute on each destination. When navigating to one of these destinations, a containing fragment is created to display the composable content.
  // In HomeScreen.kt
  @Composable
  fun HomeScreen() {
    // Your Composable content here
  }

  // In your navigation.xml
  <composable
    android:id="@+id/home_screen"
    android:name="com.example.HomeScreenKt\$HomeScreen" />

Другие изменения

  • Navigation Compose now depends on Compose 1.7.0.
  • Navigation now provides a new CollectionNavType<T> class, a subclass of NavType<T> for collection-based arguments such as list, arrays, maps. All of the default NavType arrays ( IntArrayType , LongArrayType , FloatArrayType , BoolArrayType , and StringArrayType ) now inherit from this new class.
  • NavType now has built-in support for Lists of Int, String, Boolean, Float, and Long.

Version 2.8.0-rc01

21 августа 2024 г.

androidx.navigation:navigation-*:2.8.0-rc01 is released. Version 2.8.0-rc01 contains these commits .

Исправления ошибок

  • Fix navigation crash when passing in top level Enum classes as type safe arguments. ( I0ba76 , b/358137294 )
  • Navigation 2.8 now correctly works with SDK 34 and will not swap over to SDK 35 until the 2.9 release along with the rest of the AndroidX libraries. ( b/358798728 )

Version 2.8.0-beta07

7 августа 2024 г.

androidx.navigation:navigation-*:2.8.0-beta07 is released. Version 2.8.0-beta07 contains these commits .

Известные проблемы

  • Due to b/358137294 , only Enums nested in another class are supported out of the box. Top level Enums will be supported in the next release.

Исправления ошибок

  • When navigating to duplicate or shared destinations, navigation will prioritize going to the closest matching destination from the current location in the graph. ( Ic89a4 , b/352006850 )
  • Navigation in safe args now has added a new NavType.EnumType . This means Enum types no longer require custom NavType s. Note that the Enum 's SerialName must be the default fully qualified name. ( I66d22 , b/346475493 )
  • Navigation in safe args has added built-in support for nullable argument types including Int? , Long? , Float? , Boolean? , and Enum<*>? . ( I32d13 , I1c580 , Ifba66 , I978b0 , Ide076 , b/351994237 )
  • The NavGraph 's startDestination will now use the default argument values if the startDestination route passed to the NavGraph is exactly equal to the startDestination.route . ( I13762 , b/354046047 )

Version 2.8.0-beta06

24 июля 2024 г.

androidx.navigation:navigation-*:2.8.0-beta06 is released. Version 2.8.0-beta06 contains these commits .

Исправления ошибок

  • Fixed an issue where the WrongStartDestinationType lint checks did not check for Companion objects on the passed in class type, causing lint to fail to detect the error. ( I92b09 )

Version 2.8.0-beta05

10 июля 2024 г.

androidx.navigation:navigation-*:2.8.0-beta05 is released. Version 2.8.0-beta05 contains these commits .

Исправления ошибок

  • Fix singleTop navigation crash when nested NavGraphs share the same startDestination route. ( I17b94 , b/294408596 )

Version 2.8.0-beta04

26 июня 2024 г.

androidx.navigation:navigation-*:2.8.0-beta04 is released. Version 2.8.0-beta04 contains these commits .

Исправления ошибок

  • Navigation now supports navigating with empty strings in path arguments. ( Ic5dbd , b/339481310 )
  • Improve error message for custom serializers declared directly on class fields via @Serializable(with =...) to clarify that this is currently an unsupported feature. ( I052b0 , b/341319151 )
  • SavedStateHandleFactory test api can now be used in non-android tests but will require Robolectric to support argument parsing with Bundles. ( I76cdc , b/340966212 )
  • Fixed crash from restoring state when resuming the app after process death with using Type-Safe Navigation in Compose. ( Ia8f38 , b/341801005 )
  • Fixed an issue in Navigation Compose where after canceling the Predictive Back Gesture, the NavBackStackEntry that the user returns to never returns back to the RESUMED Lifecycle State. This also ensures the returning destination correctly animates back in instead of snapping into place after a fling. ( I97a0c , b/346608857 )
  • When using Predictive back with Navigation Compose, the destination being popped will now have the proper z-order, correctly animating on top of the incoming destination. ( I2077b , b/345993681 )

Version 2.8.0-beta03

12 июня 2024 г.

androidx.navigation:navigation-*:2.8.0-beta03 is released. Version 2.8.0-beta03 contains these commits .

Изменения API

  • CollectionNavType has a new abstract emptyCollection() method. Override this to handle an empty collection passed in as an argument. ( Ie4d84 , b/341723133 )

Исправления ошибок

  • Added documentation on NavType.serializeAsValue and serializeAsValues to highlight that the final outputs should be Uri encoded. ( Ida6bd , b/344943214 )
  • Fixed crash when calling toRoute<T> with a null CollectionNavType argument. When navigating with a null CollectionNavType , the output argument will be the default value declared on your Serializable class, or the return value of emptyCollection() if there is no default value. ( I84158 , Id630f , b/342672856 )

Version 2.8.0-beta02

29 мая 2024 г.

androidx.navigation:navigation-*:2.8.0-beta02 is released. Version 2.8.0-beta02 contains these commits .

Исправления ошибок

  • Fixed ClassCastException crash when using NavBackStackEntry.toRoute with a nullable custom NavType . ( I1c29b , b/342239473 )
  • Fixed Navigation back stack state restoration issues caused when attempting to restore a back stack entry that is not reachable via id from the current destination. Since routes are backed by ids, destinations built with routes were also affected. This also fixes a crash caused by calling clearBackStack() that had the same underlying issue. ( I423c3 , b/339908057 )

Version 2.8.0-beta01

14 мая 2024 г.

androidx.navigation:navigation-*:2.8.0-beta01 is released. Version 2.8.0-beta01 contains these commits .

Изменения API

  • SavedStateHandle.toRoute() now takes in a typeMap parameter for custom argument types. ( Ie39fb , b/339026523 )
  • Added a test API to navigation-testing to to create a SavedStateHandle from a Kotlin Serializable object. ( Id4867 , b/339080702 )

Исправления ошибок

  • Missing parameter docs for Navigation Kotlin DSL functions have been added. ( I26a36 )

Version 2.8.0-alpha08

1 мая 2024 г.

androidx.navigation:navigation-*:2.8.0-alpha08 is released. Version 2.8.0-alpha08 contains these commits .

Safe Args in Navigation Compose

This functionality uses Kotlin Serialization to allow you to define destinations in your navigation graph via type safe objects and data classes:

  // Define a home destination that doesn't take any arguments
  @Serializable
  object Home

  // Define a profile destination that takes an ID
  @Serializable
  data class Profile(val id: String)

  // Now define your NavHost using type safe objects
  NavHost(navController, startDestination = Home) {
      composable<Home> {
          HomeScreen(onNavigateToProfile = { id ->
              navController.navigate(Profile(id))
          })
      }
      composable<Profile> { backStackEntry ->
          val profile: Profile = backStackEntry.toRoute()
          ProfileScreen(profile)
      }
  }

See the Navigation Compose meet Type Safety blog post for more information.

Новые возможности

  • The navigation-fragment-compose artifact now provides a LocalFragment composition local to composable methods within a ComposableFragment . ( If35e5 )
  • NavType now has built-in support for Lists of Int, String, Boolean, Float, and Long. ( I4b6dd , Ia914c , b/188693139 )

Version 2.8.0-alpha07

17 апреля 2024 года

androidx.navigation:navigation-*:2.8.0-alpha07 is released. Version 2.8.0-alpha07 contains these commits .

Новые возможности

  • Adds a new navigation-fragment-compose artifact that includes a ComposableNavHostFragment alternative to NavHostFragment that allows you to add composable destinations to your Navigation XML files. Each composable destination must be expressed as a top-level, no argument @Composable method whose fully qualified name is used as the android:name attribute on each destination. When navigating to one of these destinations, a containing fragment is created to display the composable content. ( I0ef2e , b/265480755 )

    // In HomeScreen.kt
    @Composable
    fun HomeScreen() {
      // Your Composable content here
    }
    
    // In your navigation.xml
    <composable
      android:id="@+id/home_screen"
      android:name="com.example.HomeScreenKt\$HomeScreen" />
    

Изменения API

Version 2.8.0-alpha06

3 апреля 2024 г.

androidx.navigation:navigation-*:2.8.0-alpha06 is released. Version 2.8.0-alpha06 contains these commits .

Изменения API

Исправления ошибок

  • NavHost now used Alignment.TopStart as the default contentAlignment argument. This puts it in line with the default for AnimatedContent and fixes some instances of an unexpected scale from center transition. ( I09e72 , b/330111602 )
  • When flicking the predictive back gesture while using Navigation Compose, the NavHost will now correctly complete the custom transition instead of immediately finishing. ( I99017 , b/327292110 )

Version 2.8.0-alpha05

20 марта 2024 г.

androidx.navigation:navigation-*:2.8.0-alpha05 is released. Version 2.8.0-alpha05 contains these commits .

Новые возможности

  • You can now pass arguments to NavGraph 's startDestination directly in the startDestination route without relying on defaultValue . This applies to nested NavGraph startDestinations as well. ( I0e0b5 , b/109505019 , b/188693139 )

Изменения API

  • Added new abstract CollectionNavType<T> class, a subclass of NavType<T> for collection-based arguments such as list, arrays, maps. ( Ic6d63 , b/188693139 )
  • All of the default NavType arrays ( IntArrayType , LongArrayType , FloatArrayType , BoolArrayType , and StringArrayType ) are now of type CollectionNavType ( Idcf79 , b/188693139 )
  • NavType now provides a new open valueEquals API that determines if two values of the same type are equal to one another. ( I6cb97 , b/327229511 )

Исправления ошибок

  • Query parameters in deep links now allows values in the form of curly braces around argument name (ie {argName} ) as valid values for string-based NavTypes . This fixes an issue where such a value would be considered invalid (or absence of value) for all types. ( I18302 , b/327274038 )
  • NavController functions that support routes such as navigate or popBackStack can now properly match routes filled with arguments of Array NavTypes . ( Iea805 , b/327229511 )

Version 2.8.0-alpha04

6 марта 2024 года

androidx.navigation:navigation-*:2.8.0-alpha04 is released. Version 2.8.0-alpha04 contains these commits .

Новые возможности

  • You can now specify the SizeTranform for your transitions in Navigation Compose by defining them as part of the initialization for the composable and/or navigation functions. ( I91062 , b/296912651 )

Исправления ошибок

  • Fixed an issue where NavHost in Compose Navigation failed to properly show the transition when using System Back without a gesture. ( Iceeae , b/325998468 )

Version 2.8.0-alpha03

21 февраля 2024 г.

androidx.navigation:navigation-*:2.8.0-alpha03 is released. Version 2.8.0-alpha03 contains these commits.

Изменения API

  • NavBackStackEntry.savedStateHandle is now marked as @MainThread as it uses code that is required to be on the main thread anyway. ( Ibb988 , b/299523245 )

Исправления ошибок

  • Fixed an issue in Navigation that caused NavGraph ViewModels to be DESTROYED too soon because the associated entry's ViewModel was not part of the saved state. ( Ib6bb7 , b/317581849 )

Dependency Update

Version 2.8.0-alpha02

7 февраля 2024 года

androidx.navigation:navigation-*:2.8.0-alpha02 is released. Version 2.8.0-alpha02 contains these commits.

Новые возможности

  • Navigation Compose now provides support for Predictive in-app back via the new SeekableTransitionState APIs from compose-animation. This allows you to use the back gesture to see the previous destination with your custom Transition before deciding to either commit the transaction via the completed gesture or cancel. ( I8b8e9 )

Version 2.8.0-alpha01

24 января 2024 г.

androidx.navigation:navigation-*:2.8.0-alpha01 is released. Version 2.8.0-alpha01 contains these commits.

Исправления ошибок

  • Fixed BackStackState leak where multiple saveState calls on a destination would result in multiple states to be saved, but only the first one could be restored. ( I598b0 , b/309559751 )
  • Fixed an issue where non-String arguments would not be properly displayed when using the NavigationUI helpers to populate the title of app bars. ( #636 , b/316676794 )

Dependency Update

External Contribution

  • Thanks SimonMarquis for fixing the display issue for non-String arguments when using the NavigationUI helpers to populate the title of app bars.

Version 2.7.7

Version 2.7.7

7 февраля 2024 года

androidx.navigation:navigation-*:2.7.7 is released. Version 2.7.7 contains these commits.

Исправления ошибок

  • Backported from Navigation 2.8.0-alpha01 : Fixed BackStackState leak where multiple saveState() calls on a single NavBackStackEntry would result in multiple states being saved, but only the first saved state could be restored. ( I598b0 , b/309559751 )
  • Backported from Navigation 2.8.0-alpha01 : Fixed an issue where non-String arguments would not be properly displayed when using the NavigationUI helpers to populate the title of app bars. ( #636 , b/316676794 )

External Contribution

  • Thanks SimonMarquis for fixing the display issue for non-String arguments when using the NavigationUI helpers to populate the title of app bars.

Version 2.7.6

Version 2.7.6

13 декабря 2023 года

androidx.navigation:navigation-*:2.7.6 is released. Version 2.7.6 contains these commits.

Исправления ошибок

  • The NavGraph equals() function now correctly considers the nodes of the other graph instead of just the calling one. This will ensure that graphs that have nodes with different ids will no longer be considered equal ( I401cb , b/311414915 )

Version 2.7.5

Version 2.7.5

1 ноября 2023 г.

androidx.navigation:navigation-*:2.7.5 is released. Version 2.7.5 contains these commits.

Улучшение производительности

  • Greatly improved the performance (both in terms of time and number of allocations) of comparing two graphs. This means that calls such as setGraph which internally compare the new graph to the existing one are much faster and result in fewer skipped frames. Thank you Michał Z for the thorough analysis that led to this improvement. ( I6ad62 )
  • NavHost will now render the start destination on the first composition pass instead of needing to wait for the second pass to read updated state. ( I439a7 , b/304852206 )

Исправления ошибок

  • Fixed an issue where your back stack would be popped if you called setGraph more than once with the exact same graph only if there was a destination in your graph that contained an action linking two destinations. ( Ieaed7 )
  • Dialogs that were navigated to and dismissed in quick succession will no longer leak into the list of NavController.visibleEntries . ( I67586 , b/287969970 )
  • When an entry is popped followed by a configuration change, the entry's ViewModel will now be cleared properly if saveState is false. ( Idf242 , b/298164648 )
  • Fixed an issue where NavController could handle the same deep link more than once if the back stack was entirely empty before a configuration change or call to setGraph only when the incoming Intent had the FLAG_ACTIVITY_NEW_TASK flag set. ( I73c7f )

Обновления зависимости

  • Navigation with Fragments now depends on Fragment 1.6.2 , fixing an issue where the ViewModel instances of nested fragments would not be cleared when calling clearBackStack .

Version 2.7.4

Version 2.7.4

4 октября 2023 г.

androidx.navigation:navigation-*:2.7.4 is released. Version 2.7.4 contains these commits.

Новые возможности

  • Added support for popUpTo to use routes with arguments to allow popping back to a specific entry that uses those exact arguments, matching the support found in popBackStack . ( I731f4 , b/299255572 )

Исправления ошибок

  • Fix issue where interrupting a navigate with another navigate with popUpTo will cause FragmentNavigator to crash. ( I3c848 , b/301887045 )
  • Fixed issue where system back press caused the currentDestination to not be updated correctly to match the displayed Fragment. ( Id0d6c , b/289877514 )
  • DialogFragment lifecycle will now properly move to RESUMED state when the dialog above it is dismissed. ( I88f0d , b/301811387 )

Version 2.7.3

Version 2.7.3

20 сентября 2023 г.

androidx.navigation:navigation-*:2.7.3 is released. Version 2.7.3 contains these commits.

Исправления ошибок

  • Fixed an issue in Navigation with Fragments that caused the visibleEntries list to contain incorrect entries. ( I5caa9 , b/288520638 )
  • Fixed an issue that caused Floating Window destination (ie Dialogs , Bottomsheets , etc) to never get a RESUMED Lifecycle callback. ( I3b866 , b/287505132 )

Version 2.7.2

Version 2.7.2

6 сентября 2023 года

androidx.navigation:navigation-*:2.7.2 is released. Version 2.7.2 contains these commits.

Исправления ошибок

  • Navigation now depends on Lifecycle 2.6.2 , fixing an interaction between rememberSaveable and Navigation Compose's NavHost that would cause the rememberSaveable state of destinations and any ViewModel owned SavedStateHandle instances from being properly restored after process death and recreation. ( b/298059596 , b/289436035 )
  • Fixed an issue when showing multiple dialogs in Navigation Compose simultaneously where the partially obscured dialogs (eg, not the topmost dialog) would be in the CREATED Lifecycle state rather than the STARTED state. ( aosp/2728520 , b/289257213 )
  • Fixed an issue when showing multiple dialogs in Navigation Compose simultaneously where dismissing the topmost dialog would cause the new topmost dialog to be stuck in the STARTED Lifecycle state rather than correctly moving to RESUMED . ( aosp/2629401 , b/286371387 )
  • Navigation Safe Args no longer instantiates its task eagerly if it is not actually being executed. ( I0e385 , b/260322841 )

Dependency Update

  • Navigation Compose now depends on Compose 1.5.1.

Version 2.7.1

Version 2.7.1

23 августа 2023 г.

androidx.navigation:navigation-*:2.7.1 is released. Version 2.7.1 contains these commits.

Исправления ошибок

  • Fixed an issues in Navigation with Compose where when using a Scaffold it was possible to get an error for trying to access a Lifecycle.State.DESTROYED ViewModel . ( I1dc11 , b/268422136 )

Version 2.7.0

Version 2.7.0

9 августа 2023 г.

androidx.navigation:navigation-*:2.7.0 is released. Version 2.7.0 contains these commits.

Important changes since 2.6.0

Animations from Accompanist

Now that AnimatedContent is stable, we were able to move the code from Accompanist Navigation Animation back into Navigation Compose itself.

This means all of the support for setting custom transitions that existed in AnimatedNavHost is directly supported in NavHost .

No additional changes will be made to Accompanist Navigation Animation and we'll be formally deprecating it soon, along with guidance on how to migrate back to Navigation Compose itself, but it'll be the inverse of the migration guide with no other API changes required if you're already using the latest Accompanist alpha ( 0.31.2-alpha ). ( b/197140101 )

Исправления ошибок

  • NavHost in Navigation Compose now correctly intercepts system back calls even after the Activity has been STOPPED and RESUMED. ( Icb6de , b/279118447 )

Обновления зависимости

  • Navigation now depends on Compose 1.5.0 up from 1.1.0 .

Version 2.7.0-rc01

26 июля 2023 г.

androidx.navigation:navigation-*:2.7.0-rc01 is released. Version 2.7.0-rc01 contains these commits.

Исправления ошибок

  • Fixed an issue where the EnterTransition and ExitTransition lambdas created as part of the NavHost could potentially remain in memory even after the NavHost is removed from composition. ( I893d0 )

Известные проблемы

  • There is an issue from Navigation 2.6.x that when navigating with popUpTo it is possible to cause an IllegalArgumentException . It is possible that this exception can be avoided by restructuring your graph, similar to the advice suggested here . ( b/287133013 )

Version 2.7.0-beta02

28 июня 2023 г.

androidx.navigation:navigation-*:2.7.0-beta02 is released. Version 2.7.0-beta02 contains these commits.

Исправления ошибок

  • Navigation Compose now has the right z-order for custom transitions that use navigate with the popUpTo option.( /Ib1c3a , b/285153947 )

Version 2.7.0-beta01

7 июня 2023 г.

androidx.navigation:navigation-*:2.7.0-beta01 is released. Version 2.7.0-beta01 contains these commits.

Исправления ошибок

  • NavHost in Navigation Compose now correctly intercepts system back calls even after the Activity has been STOPPED and RESUMED . ( Icb6de , b/279118447 )

Version 2.7.0-alpha01

24 мая 2023 г.

androidx.navigation:navigation-*:2.7.0-alpha01 is released. Version 2.7.0-alpha01 contains these commits.

Animations from Accompanist

Now that AnimatedContent is stable, we were able to move the code from Accompanist Navigation Animation back into Navigation Compose itself.

This means all of the support for setting custom transitions that existed in AnimatedNavHost is directly supported in NavHost .

No additional changes will be made to Accompanist Navigation Animation and we'll be formally deprecating it soon, along with guidance on how to migrate back to Navigation Compose itself, but it'll be the inverse of the migration guide with no other API changes required if you're already using the latest Accompanist alpha ( 0.31.2-alpha ). ( b/197140101 )

Исправления ошибок

  • From Navigation 2.6.0-rc02 : Fixed an issue with Navigation in Fragments where navigating with popUpTo and popping a fragment off the back stack without recreating its view would cause system back to stop working. ( Ieb8d4 , b/281726455 )

Обновления зависимости

  • Navigation now depends on Compose 1.5.0-beta01 .

Version 2.6.0

Version 2.6.0

7 июня 2023 г.

androidx.navigation:navigation-*:2.6.0 is released. Version 2.6.0 contains these commits.

Important changes to Navigation since 2.5.0

  • NavBackStackEntry 's arguments and the arguments passed to an OnDestinationChangedListener are now only a copy of the immutable arguments that were created when you navigated to the destination. This means any changes made to those Bundles will not be reflected in subsequent accesses to the arguments or other OnDestinationChangedListener instances.
  • NavDeepLink now supports default values for arrays, which allows support for repeated query params that will map to the argument's array type. NavType also now includes a default method which can be overridden to combine two parsed values.
  • Custom subclasses of NavType can now override serializeAsValue to serialize a value into a String, allowing both serialization and deserialization (via parseValue ) to be entirely encapsulated in the NavType class. StringType now overrides this method to call Uri.encode on the given String .

Important changes to Navigation Compose since 2.5.0

  • When previewing a composable with NavHost , it will now show the NavGraph's startDestination by default.
  • NavController.popBackStack(route) , NavController.getBackStackEntry(route) , NavController.clearBackStack(route) now all support routes with arguments partially or fully filled in. Note that the arguments have to be an exact match with the entry's arguments.
  • Attempting to create an empty NavDeepLink using the navDeepLink Kotlin DSL will now result in a lint warning indicating that a deep link needs an uri, action, and/or mimetype to be valid.

Important changes to Navigation with Fragments since 2.5.0

  • NavHostFragment no longer intercepts the system back button itself. This allows the underlying FragmentManager to handle system back. This allows Fragment 1.7.0-alpha01 and higher to provide an In-App Predictive Back animation on Android U devices.
  • When using Navigation with Fragments, attempting to manually do a FragmentTransaction that adds a fragment to the FragmentManager 's back stack will now throw an IllegalArgumentException . You should always add fragments via the navigate() API.
  • When using the exact string ${applicationId} as the placeholder in the app:data and app:dataPattern attributes in the activity element of a navigation XML file, the placeholder will be automatically filled in with the packageName of the context upon inflation.
  • The FragmentNavigator now uses the transition APIs when navigating and popping NavBackStackEntries . This means that the NavBackStackEntry Lifecycle will now wait for the entering and exiting fragment special effects to complete before moving their final Lifecycle.State .
  • The DialogFragmentNavigator now uses the transition APIs when navigating and popping NavBackStackEntries . This means that the NavBackStackEntry Lifecycle will now wait for the DialogFragment Lifecycle to move to DESTROYED before moving to DESTROYED itself.
  • NavHostFragment now allows you to retrieve the NavController as soon as the NavHostFragment is attached to the FragmentManager , rather than only after onCreate() .
  • Navigation's support for Dynamic Feature Modules now depend on the granular Play Feature Delivery Library.
  • Navigation Safe Args now depends on Android Gradle Plugin version 7.3.0. This means it is now only compatible with versions 7.3.0+.

Important changes to NavigationUI since 2.5.0

  • When passing the ID of a navigation graph to AppBarConfiguration (such as via a Menu ), NavigationUI now only considers the start destination of that navigation graph as a top level destination, rather than incorrectly marking every destination within the graph as a top level destination. The behavior of passing the ID of an individual destination is unchanged. This same functionality is available to your own code via the new isTopLevelDestination function on AppBarConfiguration .
  • The setupWithNavController integrations in NavigationUI for working with the top app bar will now parse R.string values for ReferenceType arguments found in your android:label into their String values instead of outputting the auto-generated resource integer.
  • NavigationUI now provides logs when it fails to navigate via a selected MenuItem .

Version 2.6.0-rc02

24 мая 2023 г.

androidx.navigation:navigation-*:2.6.0-rc02 is released. Version 2.6.0-rc02 contains these commits.

Исправления ошибок

  • Fixed an issue with Navigation in Fragments where navigating with popUpTo and popping a fragment off the back stack without recreating its view would cause system back to stop working. ( Ieb8d4 , b/281726455 )

Version 2.6.0-rc01

10 мая 2023 г.

androidx.navigation:navigation-*:2.6.0-rc01 is released. Version 2.6.0-rc01 contains these commits.

Исправления ошибок

  • Fixed an issue in Navigation with fragments where removing a fragment via navigate with popUpTo in its onResume() lifecycle callback would cause an IllegalStateException . ( I21884 , b/279644470 )

Version 2.6.0-beta01

19 апреля 2023 года

androidx.navigation:navigation-*:2.6.0-beta01 is released. Version 2.6.0-beta01 contains these commits.

Новые возможности

  • NavBackStackEntry now provides a custom toString implementation. ( Iff00b )

Исправления ошибок

  • When using Navigation with Fragments, attempting to manually do a FragmentTransaction that adds a fragment to the FragmentManager 's back stack will now throw an IllegalArgumentException . You should always add fragments via the navigate() API. ( I6d38e )
  • When there is a navigate that adds an entry and a popBackStack that removes it in the same frame, the resulting top entry on the back stack will now consistently make it back to the RESUMED Lifecycle.State . ( Id8067 , b/276495952 )

Version 2.6.0-alpha09

5 апреля 2023 года

androidx.navigation:navigation-*:2.6.0-alpha09 is released. Version 2.6.0-alpha09 contains these commits.

Исправления ошибок

  • Fixed checks for invalid route such that if a NavDestination contains non-nullable NavArgument , this destination's route must contain placeholders for args named the same as the non-nullable NavArgument . ( Ic62bf , b/274697949 )
  • Deeplink navigations based on Action/MimeType will now fail if the navigation operation is missing a non-nullable NavArgument required by the NavDestination that the Action/MimeType matches with. ( Ibfa17 , b/271777424 )
  • When NavController sets a graph with the same route and destinations as the previous graph, it now properly replaces its current graph nodes and its back stack destinations with new instances. This fixes a crash when using onLaunchSingleTop without saving state in Navigation Compose. This also fixes an error where navigating to destinations associated with the root graph builds and incorrect back stack. ( I5bc58 , b/275258161 , b/275407804 )

Version 2.6.0-alpha08

22 марта 2023 г.

androidx.navigation:navigation-*:2.6.0-alpha08 is released. Version 2.6.0-alpha08 contains these commits.

Новые возможности

  • NavHostFragment now allows you to retrieve the NavController as soon as the NavHostFragment is attached to the FragmentManager , rather than only after onCreate() . ( Ic6382 , b/220186282 )

Исправления ошибок

  • Fixed a NullPointerException when popping a nested graph that includes a non-nullable argument. ( 6b3581 , b/249988437 )
  • When using system back after doing a navigate with popUpTo , the state of the NavController will pop to the correct entry. ( I3a8ec , b/270447657 )
  • FragmentNavigator will now properly pop entries when the back stack is popped via system back or popBackStack() and whether or not the transaction uses effects for the fragment. ( I81bdf )
  • Adding fragments to the FragmentNavigator 's FragmentManager without using navigation will no longer cause a crash. ( b17204 , b/274167493 )

Обновления зависимости

Version 2.6.0-alpha07

8 марта 2023 г.

androidx.navigation:navigation-*:2.6.0-alpha07 is released. Version 2.6.0-alpha07 contains these commits.

Исправления ошибок

  • The getBackStackEntry , popBackStack , clearBackStack API variants that take routes now take route patterns with nullable arguments and nullable query params ( I22294 , b/269302500 )
  • Fixed an issue where calling clearBackStack() from the NavController would not clear the saved state in the fragment manager associated with the cleared back stack. ( Ic1cce , b/271190202 )
  • Fixed a regression in 2.6.0-alpha06 that caused the wrong MenuItem in the BottomNavigationView to be highlighted when using System back between tabs. ( I634f6 , b/270447657 )
  • Fixed regression in 2.6.0-alpha06 that caused NavBackStackEntry s not to be moved to the RESUMED state when using Animation s. ( Ib3589 , b/269646882 )

Version 2.6.0-alpha06

February 22, 2023

androidx.navigation:navigation-*:2.6.0-alpha06 is released. Version 2.6.0-alpha06 contains these commits.

Новые функции

  • When previewing a composable with NavHost , it will now show the NavGraph's startDestination by default. ( I2b89f )

Изменения API

  • All NavController navigate overloads are now annotated with @MainThread to ensure that they are called on the main thread. ( I2c0b0 , b/263427111 )

Исправления ошибок

  • Fixed a crash when attempting to navigate while using Dynamic Fragment Navigation. ( I3ee29 , b/268360479 )
  • Fixed bug where navigating to another fragment via system back button does not update bottom bar to the correct selected item ( If559f , b/269044426 )

Известные проблемы

  • When using Navigation with Fragments, the NavBackStackEntry 's Lifecycle fails to reach RESUMED when using Animation APIs. ( b/269646882 )
  • When using Navigation with Fragments, and navigating with BottomNavigation , if you attempt to restore a back stack with multiple entries, the BottomMenuItem is not correctly updated. ( b/270447657 )
  • When using Navigation with Fragments, after restoring the state the NavBackStackEntry Lifecycle does not get DESTROYED when its fragment is DESTROYED . ( b/270610768 )

Version 2.6.0-alpha05

8 февраля 2023 г.

androidx.navigation:navigation-*:2.6.0-alpha05 is released. Version 2.6.0-alpha05 contains these commits.

Новые возможности

  • NavController.popBackStack(route) , NavController.getBackStackEntry(route) , NavController.clearBackStack(route) now all support routes with arguments partially or fully filled in. Note that the arguments have to be an exact match with the entry's arguments. ( Iebd28 , Ic678c , I3b37b , b/257514373 )
  • The FragmentNavigator now uses the transition APIs when navigating and popping NavBackStackEntries . This means that the NavBackStackEntry Lifecycle will now wait for the entering and exiting fragment special effects to complete before moving their final Lifecycle.State . ( I3cb19 , b/238686802 )
  • The DialogFragmentNavigator now uses the transition APIs when navigating and popping NavBackStackEntries . This means that the NavBackStackEntry Lifecycle will now wait for the DialogFragment Lifecycle to move to DESTROYED before moving to DESTROYED itself. ( I53ee5 , b/261213893 )

Изменения API

  • NavigatorState now provides the prepareForTransition API to allow Navigator s to move NavBackStackEntries to intermediate Lifecycle.State s. ( I42c21 , b/238686802 )
  • You can now access the back stack associated with a NavGraphNavigator or a ComposeNavigator via a backstack property. ComposeNavigator also now exposes the onTransitionComplete() callback to mark a NavBackStackEntry that has executed a navigate or popBackStack operation as complete. ( I02062 , I718db , b/257519195 )

Исправления ошибок

  • Navigator state will now no-op when using the push/popWithTransition APIs and the entry is already being handled. ( Iadbfa , b/261213893 )
  • When using launchSingleTop with a nested NavGraph all destinations starting from original destination to its startDestination will only be properly added to the top of the backstack. ( Id4bea , b/253256629 )
  • Navigation will now properly replace the DialogFragment instance when navigating to the same destination with the launchSingleTop flag set to true. ( I45b5a , b/149572817 )
  • Navigation SafeArgs will no longer cause a compilation error when using arguments that are exactly 19 characters long. ( Id60bc , b/257110095 )

Version 2.6.0-alpha04

9 ноября 2022 г.

androidx.navigation:navigation-*:2.6.0-alpha04 is released. Version 2.6.0-alpha04 contains these commits.

Новые возможности

  • Custom subclasses of NavType can now override serializeAsValue to serialize a value into a String, allowing both serialization and deserialization (via parseValue ) to be entirely encapsulated in the NavType class. StringType now overrides this method to call Uri.encode on the given String . ( Ie5213 , b/247637434 )
  • NavigationUI now provides logs when it fails to navigate via a selected MenuItem . ( I2af5a , b/247730357 )

Исправления ошибок

  • Navigation deep links are now parsed lazily instead of on graph initialization which could improve app performance at start up. ( Iab0ab )
  • Fixed crash caused by navigating up after deep linking to a destination with null default arguments. ( I51c24 , b/243183636 )

Dependency Update

  • Navigation's support for Dynamic Feature Modules now depend on the granular Play Feature Delivery Library. ( Ib4ddc )
  • Navigation Safe Args now depends on Android Gradle Plugin version 7.3.0. This means it is now only compatible with versions 7.3.0+. ( I47e49 )

Version 2.6.0-alpha03

24 октября 2022 года

androidx.navigation:navigation-*:2.6.0-alpha03 is released. Version 2.6.0-alpha03 contains these commits.

Исправления ошибок

  • From Navigation 2.5.3 : NavHost will no longer cause a NoSuchElementException when there is no destination available for the Crossfade to compose. It will now just skip the composition. ( Ieb46e , b/253299416 )
  • From Navigation 2.5.3 : Fixed an issue where saved Compose state (eg, usages of rememberSaveable ) were not being forgotten and removed when a destination was popped off the back stack. ( I64949 )

Обновления зависимости

Version 2.6.0-alpha02

5 октября 2022 г.

androidx.navigation:navigation-*:2.6.0-alpha02 is released. Version 2.6.0-alpha02 contains these commits.

Behavior Changes

  • When passing the ID of a navigation graph to AppBarConfiguration (such as via a Menu ), NavigationUI now only considers the start destination of that navigation graph as a top level destination, rather than incorrectly marking every destination within the graph as a top level destination. The behavior of passing the ID of an individual destination is unchanged. This same functionality is available to your own code via the new isTopLevelDestination function on AppBarConfiguration . ( Ie936e , b/238496771 )

Исправления ошибок

  • The navigation:navigation-fragment component now depends on Fragment version 1.5.2 . ( I00ba4 )
  • The selected menu item will no longer be updated when navigating to a FloatingWindow destination such as a dialog. ( I4cde8 , b/240308330 )

Version 2.6.0-alpha01

September 7, 2022

androidx.navigation:navigation-*:2.6.0-alpha01 is released. Version 2.6.0-alpha01 contains these commits.

Новые возможности

  • The setupWithNavController integrations in NavigationUI for working with the top app bar will now parse R.string values for ReferenceType arguments found in your android:label into their String values instead of outputting the auto-generated resource integer. ( I5f803 , b/167959935 )
  • NavDeepLink now supports default values for arrays, which allows support for repeated query params that will map to the argument's array type. NavType also now includes a default method which can be overridden to combine two parsed values. ( Id68c3 , b/209977108 )
  • When using the exact string ${applicationId} as the placeholder in the app:data and app:dataPattern attributes in the activity element of a navigation XML file, the placeholder will be automatically filled in with the packageName of the context upon inflation. ( Iaabde , b/234223561 )
  • Attempting to create an empty NavDeepLink using the navDeepLink Kotlin DSL will now result in a lint warning indicating that a deep link needs an uri, action, and/or mimetype to be valid. ( I08d2f , b/154038883 )

Изменения API

  • Added new NavDestination extension function to parse dynamic labels with arguments in the form of android:label="{arg}" into String. Supports ReferenceType arguments by parsing R.string values into their String values. ( I07d89 , b/236269380 )

Behavior Changes

  • NavBackStackEntry's arguments and the arguments passed to an OnDestinationChangedListener are now only a copy of the immutable arguments that were created when you navigated to the destination. This means any changes made to those Bundles will not be reflected in subsequent accesses to the arguments or other OnDestinationChangedListener instances. ( I676f5 )

Исправления ошибок

  • From Navigation 2.5.2 : Dynamic Navigation now properly attempts to install Activity destinations from other modules before navigating to them. ( Ia2c16 , b/240292838 )
  • From Navigation 2.5.2 : Navigation will now properly replace the Fragment instance when navigating to the same destination and setting the launchSingleTop flag to true. ( I5a2f1 , b/237374580 )
  • From Navigation 2.5.2 : Fixed IllegalStateException caused by navigating to a double nested graph that shares a parent with a new popped start destination. ( I9f7cb , b/243778589 )

Версия 2.5

Version 2.5.3

24 октября 2022 года

androidx.navigation:navigation-*:2.5.3 is released. Version 2.5.3 contains these commits.

Исправления ошибок

  • NavHost will no longer cause a NoSuchElementException when there is no destination available for the Crossfade to compose. It will now just skip the composition. ( Ieb46e , b/253299416 )
  • Fixed an issue where saved Compose state (eg, usages of rememberSaveable ) were not being forgotten and removed when a destination was popped off the back stack. ( I64949 )

Version 2.5.2

September 7, 2022

androidx.navigation:navigation-*:2.5.2 is released. Version 2.5.2 contains these commits.

Исправления ошибок

  • Dynamic Navigation now properly attempts to install Activity destinations from other modules before navigating to them. ( Ia2c16 , b/240292838 )
  • Navigation will now properly replace the Fragment instance when navigating to the same destination and setting the launchSingleTop flag to true. ( I5a2f1 , b/237374580 )
  • Fixed IllegalStateException caused by navigating to a double nested graph that shares a parent with a new popped start destination. ( I9f7cb , b/243778589 )

Dependency Update

Version 2.5.1

27 июля 2022 года

androidx.navigation:navigation-*:2.5.1 is released. Version 2.5.1 contains these commits.

Исправления ошибок

  • Navigation Safe Args will no longer cause deprecation warnings in generated classes when using custom argument types that are saved in a Bundle . ( Id86ed , b/237725966 )

Обновления зависимости

Версия 2.5.0

29 июня 2022 г.

androidx.navigation:navigation-*:2.5.0 is released. Version 2.5.0 contains these commits.

Important changes since 2.4.0

  • CreationExtras Integration - Navigation now has the ability to provide a stateless ViewModelProvider.Factory via Lifecycle 2.5.0 's CreationExtras .

Navigation SafeArgs

  • Navigation Safe Args has upgraded the Android Gradle Plugin dependency to rely on 7.0.4 , dropping compatibility for AGP versions before 7.0 .
  • Added support for the namespace build.gradle attribute to be used instead of applicationId.

Другие изменения

  • The visibleEntries API is no longer experimental and provides a function to retrieve all of the entries whose destination is currently visible according to the NavController .

Версия 2.5.0-rc02

June 15, 2022

androidx.navigation:navigation-*:2.5.0-rc02 is released. Version 2.5.0-rc02 contains these commits.

Исправления ошибок

  • Fixed a crash caused by fast switching between bottom destinations when using the Navigation Compose NavHost . ( I3979a , b/234054916 )
  • Navigation SafeArgs will no longer crash when using an applicationIdSuffix and namespace with either no applicationId present, or when the applicationId and namespace differ. ( I754b1 , b/233119646 )
  • NavArgument now has a custom toString() function to show the internal values of the argument. ( I900a8 )

Версия 2.5.0-rc01

May 11, 2022

androidx.navigation:navigation-*:2.5.0-rc01 is released. Version 2.5.0-rc01 contains these commits.

Новые возможности

  • Added a new lint rule to warn against placing <deeplink> elements inside <activity> elements in your navigation.xml file.( Ic15a5 , b/178403185 )

Исправления ошибок

  • Composable scopes in NavHost and DialogHost are now disposed in the expected order, ie inner composabled are disposed before outer composables. ( I157e6 )
  • Navigation SafeArgs now uses PathSensitivity.RELATIVE in the ArgumentsGenerationTask to allow for cache relocatability. This means the cache entry can now be re-used from a CI build to a local build. ( I5f67c , b/173420454 )
  • The UnrememberedGetBackStackEntryDetector lint rule has been updated to ensure that the remember call surrounding the call to getBackStackEntry() also passes in a NavBackStackEntry object as a key.( Ib7081 , b/227382831 )

Версия 2.5.0-бета01

20 апреля 2022 г.

androidx.navigation:navigation-*:2.5.0-beta01 is released. Version 2.5.0-beta01 contains these commits.

Исправления ошибок

  • DialogNavigator now uses popWithTransition when executing a dismiss() call. This fixes a race condition when using a ViewModel within dialog destination that would cause an IllegalStateException when dismissing the Dialog by either using system back or tapping outside of the dialog to exit. ( Id7376 , b/226552301 )

Обновления зависимости

  • Navigation now depends on Lifecycle 2.5.0-beta01 , fixing an IllegalStateException when nesting one NavHost within another NavHost in a non-primary bottom navigation tab when using multiple back stacks.

Версия 2.5.0-альфа04

6 апреля 2022 г.

androidx.navigation:navigation-*:2.5.0-alpha04 is released. Version 2.5.0-alpha04 contains these commits.

Изменения API

Исправления ошибок

  • NavHost now depend on visibleEntries from the NavController to determine which entries to compose. This means that when using nested NavHost the inner NavHost should now properly animate out. ( I4ba2b , b/225394514 )
  • The visibleEntries StateFlow provided by NavController is now based on the entry max Lifecycle state instead of the current Lifecycle state. This means that even if the host lifecycle of the navController goes below STARTED, the list of visible entires will remain the same. ( I9e2a8 , b/225394514 )
  • SavedStateViewFactory now supports using CreationExtras even when it was initialized with a SavedStateRegistryOwner . If extras are provided, the initialized arguments are ignored. ( I6c43b , b/224844583 )
  • NavDeepLink can now parse Uris with a single query parameter with no value. ( I0efe8 , b/148905489 )
  • Empty string are now considered as valid arguments in deep links. ( I70a0d , b/217399862 )
  • Navigation Safe Args will no longer crash when using namespaces and no AndroidManifest.xml is present. ( I17ccf , b/227229815 )

Версия 2.5.0-альфа03

23 февраля 2022 г.

androidx.navigation:navigation-*:2.5.0-alpha03 is released. Version 2.5.0-alpha03 contains these commits.

Изменения API

  • You can now pass in CreationExtras to by navGraphViewModels to create a ViewModel . ( I29217 , b/217618359 )

Исправления ошибок

  • NavDeepLinks now properly support encoded new line characters embedded in routes/deep link URIs. ( I513d1 , b/217815060 )
  • CreationExtras will now work correctly when used with NavBackStackEntries to create ViewModels. ( I69161 , b/217617710 )
  • Navigation Safe Args now supports using the namespace defined in the build.gradle in place of the package in the AndroidManifest. ( I659ef , b/217414933 )

Версия 2.5.0-альфа02

9 февраля 2022 года

androidx.navigation:navigation-*:2.5.0-alpha02 is released. Version 2.5.0-alpha02 contains these commits.

Исправления ошибок

  • From Navigation 2.4.1 : The NavHostFragment will now properly set the OnBackPressedDispatcher when using viewbinding with nested graphs. ( Ifbb51 , b/214577959 )
  • From Navigation 2.4.1 : When deep linking through multiple nested NavGraph s the back stack will now properly include intermediate start destinations. ( I504c0 , b/214383060 )

Версия 2.5.0-альфа01

January 26, 2022

androidx.navigation:navigation-*:2.5.0-alpha01 is released. Version 2.5.0-alpha01 contains these commits.

Новые возможности

Исправления ошибок

  • Fixed an issue where accessing a ViewModel created via by navGraphViewModels() from a Fragment's onCreate() would fail with an IllegalStateException . ( I8a14d )
  • NavDeepLink s will no longer unnecessarily decode args twice, meaning that the proper args are now passed to your final destination. ( I31b0a , b/210711399 )

Safe Args

  • Safe Args now depends on Android Gradle Plugin version 7.0.4. This means that Navigation Safe Args will no longer be compatible with Android Studio versions prior to 7.0, but is now compatible with Android Gradle Plugin 7.1.0 and higher. ( I41c88 , b/213086135 , b/207670704 )

Version 2.4.2

Version 2.4.2

6 апреля 2022 г.

androidx.navigation:navigation-*:2.4.2 is released. Version 2.4.2 contains these commits.

Исправления ошибок

Версия 2.4.1

Версия 2.4.1

9 февраля 2022 года

androidx.navigation:navigation-*:2.4.1 is released. Version 2.4.1 contains these commits.

Исправления ошибок

  • The NavHostFragment will now properly set the OnBackPressedDispatcher when using viewbinding with nested graphs. ( Ifbb51 , b/214577959 )
  • When deep linking through multiple nested NavGraph s the back stack will now properly include intermediate start destinations. ( I504c0 , b/214383060 )
  • Backported from Navigation 2.5.0-alpha01 : Fixed an issue where accessing a ViewModel created via by navGraphViewModels() from a Fragment's onCreate() would fail with an IllegalStateException . ( I8a14d )
  • Backported from Navigation 2.5.0-alpha01 : NavDeepLink s no longer unnecessarily decode args twice, meaning that the properly decoded args are now passed to your final destination. ( I31b0a , b/210711399 )
  • Backported from Navigation 2.5.0-alpha01 : Safe Args now depends on Android Gradle Plugin version 7.0.4. This means that Navigation Safe Args will no longer be compatible with Android Studio versions prior to 7.0, but is now compatible with Android Gradle Plugin 7.1.0 and higher. ( I41c88 , b/213086135 , b/207670704 )

Версия 2.4.0

Версия 2.4.0

January 26, 2022

androidx.navigation:navigation-*:2.4.0 is released. Версия 2.4.0 содержит эти коммиты.

Важные изменения с версии 2.3.0

  • All Navigation artifacts have been rewritten in Kotlin. This has improved the nullability of classes using generics (such as NavType subclasses). All Kotlin extension functions that used to be part of the -ktx artifacts have been moved to their respective main artifacts. The -ktx artifacts will continue to be published, but are completely empty.
  • The navigation-fragment artifact now contains a prebuilt implementation of a two pane layout via the new AbstractListDetailFragment . This fragment uses a SlidingPaneLayout to manage a list pane (which your subclass provides) and a detail pane, which uses a NavHostFragment as its implementation, as seen in our example implementation .
  • The currentBackStackEntryAsFlow() method on NavController provides a Flow that emits whenever the current NavBackStackEntry changes. This flow can be used as an alternative to manually managing an OnDestinationChangedListener .
  • NavController now offers the ability to retrieve a list of all visible NavBackStackEntry instances as a StateFlow via the experimental visibleEntries property.
  • It is now possible to extend the NavType class to create custom NavTypes. Custom types are supported only when building your navigation graph programmatically, such as via the Navigation Graph Kotlin DSL .
  • Navigation now provides findStartDestination() and getHierarchy() APIs that can be used to help implement custom NavigationUI. findStartDestination() is an extension function on NavGraph that will locate the actual start destination that will be displayed when you navigate to the graph, even if the startDestination is itself a nested NavGraph . getHierarchy() is a function on NavDestination that can be used to verify if a given destination is within the hierarchy of another.

    val matchingRoute: Boolean = destination.hierarchy.any { it.route == routeToFind }
    
  • NavigationUI methods that took a BottomNavigationView have been updated to instead take its superclass introduced in Material 1.4.0 , NavigationBarView . This allows these methods to be used with the NavigationRailView .

  • When inflating an <action> element via XML, animation attributes can use attributes pulled from your theme using the app:enterAnim="?attr/transitionEnter" syntax.

  • Safe Args now generates a fromSavedStateHandle() method for each NavArgs class. ( #122 , b/136967621 )

    class HomeViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
      // Create a HomeDestinationArgs class with type safe accessors for each argument
      // defined on your destination
      private val args = HomeDestinationArgs.fromSavedStateHandle(savedStateHandle)
    }
    

Navigation Routes and the Kotlin DSL

Previous versions of Navigation relied on each destination having a constant integer ID that would uniquely identify it from its sibling destinations and allow you to navigate() to that destination either directly or via an action. While this continues to be valid and useful, particularly in cases where you are defining your navigation graph in XML and can use auto-generated R.id constants or Safe Args (which uses those constants to generate code at build time), this system of unique integers did not capture the semantic meaning and expressiveness needed to support fully dynamic graphs built programmatically at runtime via the Navigation Kotlin DSL .

This release introduces a new option for uniquely identifying a destination in a navigation graph by its route . A route is a String that defines the unique path to a destination. All Kotlin DSL methods that took a destination ID are now deprecated and replaced with an equivalent API that takes a route.

Each route should be treated as the 'path' part of a Uri that defines that destination, eg, home , profile/{userId} , profile/{userId}/friends , etc. When the identity of a destination is associated with a specific piece of content, those dynamic arguments should be part of the route, following the same rules as implicit deep links .

All NavController APIs that used to only take an ID now have an overload that takes a route String . This includes navigate() , popBackStack() , popUpTo() , and getBackStackEntry() .

This has had some API implications:

  • The popUpTo Kotlin property on the Kotlin DSL has been deprecated in favor of popUpToId .
  • The getStartDestination() API has been deprecated in favor of getStartDestinationId() .

Unlike when navigating by ID, navigating by route follows the same rules as implicit deep links in that you can directly navigate to any destination in any nested graph, ensuring that these routes are usable in multi-module projects without explicitly adding an externally visible deep link to each destination.

Navigation Compose

The navigation-compose artifact provides integration between the Navigation Component and Jetpack Compose . It uses @Composable functions as the destinations in your application.

This release provides:

  • A NavHost composable that allows you to construct your navigation graph via a Kotlin DSL, using composable and dialog destinations, plus support for optional Navigators such as those from Accompanist Navigation Material .
  • Mandatory support for crossfading between destinations. Accompanist Navigation Animation can be used to control the enter and exit transitions using experimental Compose APIs.
  • Scoping of a Lifecycle to each composable destination. Each destination only reaches the RESUMED state when any entering transitions finish and immediately drops to STARTED when any exiting transitions start, thus allowing you to avoid all IllegalStateException and multi-touch issues by only triggering a navigate call when the Lifecycle is RESUMED .
  • Scoping of ViewModel (via the viewModel() API of Lifecycle ViewModel Compose 2.4.0 or hiltViewModel() of Hilt Navigation Compose 1.0.0 at the destination level, providing a scope that survives configuration changes and being on the back stack (when your Composable content is otherwise disposed) and a signal in the ViewModel's onCleared() that indicates the permanent disposal and cleaning up of state associated with that NavBackStackEntry .
  • Scoping of rememberSaveable state at a destination level, ensuring that all composable state is saved and restored automatically when you return to a destination.
  • Full support for saving and restoring the state of the NavController and its destination's state after process death and recreation.
  • Automatic integration with the system back button.
  • Support for passing arguments, attaching deep links to destinations, and returning a result to previous destinations.

  • Compose specific helpers in rememberNavController() and currentBackStackEntryAsState() to allow hoisting state and connecting the NavController to composables outside of the NavHost (such as a bottom navigation bar).

val navController = rememberNavController()
Scaffold { innerPadding ->
    NavHost(navController, "home", Modifier.padding(innerPadding)) {
        composable("home") {
            // This content fills the area provided to the NavHost
            HomeScreen()
        }
        dialog("detail_dialog") {
            // This content will be automatically added to a Dialog() composable
            // and appear above the HomeScreen or other composable destinations
            DetailDialogContent()
        }
    }
}

See the Compose Navigation guide for more information.

Multiple back stacks

The NavController is responsible for managing the back stack of destinations, adding destinations to the back stack when you navigate() to them and removing them when you call popBackStack() or trigger the system back button. The existing NavOptions class and the integration into <action> elements in the navigation graph XML has been expanded to support saving and restoring the back stack.

As part of this change, the NavigationUI methods of onNavDestinationSelected() , BottomNavigationView.setupWithNavController() and NavigationView.setupWithNavController() now automatically save and restore the state of popped destinations, enabling support for multiple back stacks without any code changes. When using Navigation with Fragments, this is the recommended way to integrate with multiple back stacks.

The underlying APIs for saving and restoring the state are exposed via a number of surfaces:

  • In Navigation XML, the <action> element can now use the boolean attributes of app:popUpToSaveState and app:restoreState to save the state of any destinations popped via app:popUpTo and restore the state associated with the destination passed as the app:destination :

    <action
      android:id=”@+id/swap_stack”
      app:destination=”@id/second_stack”
      app:restoreState=”true”
      app:popUpTo=”@id/first_stack_start_destination”
      app:popUpToSaveState=”true” />
    
  • In the navOptions Kotlin DSL , you can add the restoreState boolean property and the saveState boolean property on the popUpTo builder :

    // Use the navigate() method that takes a navOptions DSL Builder
    navController.navigate(selectedBottomNavRoute) {
      launchSingleTop = true
      restoreState = true
      popUpTo(navController.graph.findStartDestination().id) {
        saveState = true
      }
    }
    
  • In manually building a NavOptions object via the NavOptions.Builder , you can use the setRestoreState() and new overload to setPopUpTo() that takes an additional saveState parameter.

    NavOptions navOptions = new NavOptions.Builder()
      .setLaunchSingleTop(true)
      .setRestoreState(true)
      .setPopUpTo(NavGraph.findStartDestination(navController.getGraph()).getId(),
        false, // inclusive
        true) // saveState
      .build();
    navController.navigate(selectedBottomNavId, null, navOptions);
    
  • Programmatic calls to popBackStack() can now include an additional saveState parameter.

  • You can use the clearBackStack() method to clear any state that was saved with popBackStack() or popUpToSaveState .

In all cases, the NavController will save and restore the state of each NavBackStackEntry , including any navigation destination scoped ViewModel instances. The Navigator APIs have been updated to enable each Navigator to support saving and restoring their own state.

Изменения в поведении

  • NavDeepLinkBuilder now adds PendingIntent.FLAG_IMMUTABLE to the PendingIntent returned by createPendingIntent() , ensuring that this API works as expected when targeting Android 12.
  • Navigation now depends on Lifecycle 2.3.1 and now marks setGraph() , popBackStack() , navigateUp() , and navigate() , the methods that update the NavBackStackEntry Lifecycle , as @MainThread , aligning Navigation with the main thread enforcement introduced in Lifecycle 2.3.0 .
  • Deep links now verify that all required arguments (those without default values) are present in the Uri .
  • NavDeepLink parsed arguments now consider pound signs in the same way as question marks as a separator between path segments, preventing an argument from spanning across the pound sign.
  • When generating actions, Kotlin code generated from Safe Args now puts arguments without default values before those with default values as parameters.
  • When generating arguments, Safe Args now puts parameters without default values before those with default values.
  • Safe-Args now depends on Android Gradle Plugin 4.2.0. This means you should no longer get the using applicationIdTextResource warning.

Известные проблемы

  • Fixed in Navigation 2.5.0-alpha01 : accessing a ViewModel created via by navGraphViewModels() from a Fragment's onCreate() will fail with an IllegalStateException . ( b/213504272 )
  • Fixed in Navigation 2.5.0-alpha01 : Safe Args 2.4.0 is incompatible with Android Gradle Plugin 7.1.0 and higher. ( b/213086135 )
  • Deep linking with multiple nested nav graphs doesn't correctly create the full backstack. ( b/214383060 )

Версия 2.4.0-rc01

15 декабря 2021 г.

androidx.navigation:navigation-*:2.4.0-rc01 is released. Версия 2.4.0-rc01 содержит эти коммиты.

Изменения в поведении

  • NavDeepLink parsed arguments now consider pound signs in the same way as question marks as a separator between arguments. ( I21309 , b/180042703 )

Исправления ошибок

  • Deeplinks will no longer ignore arguments with values that are the same as the name of the placeholder. ( If8017 , b/207389470 )
  • NavController will no longer crash when popping a nested destination using transitions after the NavController has been restored. ( I0f7c9 , b/205021623 )
  • The error message when using an invalid startDestination will now default to the start destination's route if one is available. ( I86b9d , b/208041894 )

Navigation Compose Bug Fixes

  • Fixed potential crash caused by fast switching between the start destination and another destination using bottom nav menu items. ( Ic8976 , b/208887901 )
  • Dialog destination are now properly restored on top of the screen after config changes or process death. ( I4c0dc , b/207386169 )
  • Fixed an issue where attempting to retrieve a ViewModel from a dialog's NavBackStackEntry would fail when the dialog was dismissed. ( I6b96d , b/206465487 )
  • Fixed an issue when using activity destinations with Navigation Compose's NavHost that would result in infinite recompositions. ( I8f64c )
  • Fixed a leak in Navigation Compose where it was holding on to a reference of the old activity after a config change or process death. ( I4efcb , b/204905432 )

Safe Args Bug Fixes

  • SafeArgs no longer crashes when attempting to restore custom parcelable arrays after process death. ( I618e8 , b/207315994 )
  • Fixed a bug in safe args that would not allow boolean arrays to have a null value. ( I8c396 , b/174787525 )

Version 2.4.0-beta02

November 3, 2021

androidx.navigation:navigation-*:2.4.0-beta02 is released. Version 2.4.0-beta02 contains these commits.

Изменения API

  • The handling of both explicit and implicit deep links now automatically adds the saveState flag when navigating to another graph, ensuring that code such as NavigationUI.setupWithNavController and code using multiple back stacks works as expected. ( Ic8807 )

Behavior Changes

  • Deep link patterns are now compiled lazily in NavDeepLink instead of during inflation. This should improve the inflation time of navigation graphs that include deep links. ( b8d257 , b/184149935 )

Исправления ошибок

  • Fixed an issue where NavBackStackEntries were being pushed down to Lifecycle.State.CREATED after moving to Lifecycle.State.STARTED when the NavHost is added directly to the activity's setContent() . ( Ia5ac1 , b/203536683 )
  • Fixed a race condition where popping a DialogFragment destination off of the back stack before the dialog was actually shown would not actually dismiss the dialog, resulting in a crash when the errant dialog was manually dismissed by the user. ( I687e5 )
  • Fixed an issue where the onNavDestinationSelected API on NavigationUI would return true even if you didn't actually navigate() to that navigation graph. It now uses the same logic used internally by setupWithNavController to only select the MenuItem associated with the current destination using the hierarchy of the destination. ( I2b053 )

Версия 2.4.0-бета01

27 октября 2021 г.

androidx.navigation:navigation-*:2.4.0-beta01 is released. Версия 2.4.0-beta01 содержит эти коммиты.

Новые возможности

  • You can now use by navGraphViewModel with a route as an alternative to using an ID so as to better support using the Navigation Kotlin DSL with Fragments. ( I901e3 , b/201446416 )

Изменения API

  • The visibleEntries API is now experimental. ( I93f6f )

Исправления ошибок

  • ViewModels will no longer be destroyed when transitions are interrupted by navigating back and forth between the same screens ( Id52d8 , b/200817333 )
  • Nullable NavDeepLink arguments no longer require a default value when adding deep links to NavDestination s. ( I5aad4 , b/201320030 )
  • NavBackStackEntries now with different Lifecycles are not longer considered equal. This means NavHost will properly recompose all destinations when doing navigation with singleTop and when reselecting bottom menu items. ( I1b351 , b/196997433 )
  • Fixed an issue with AbstractListDetailFragment that caused the layout_width and layout_weight attributes on the list pane returned by onCreateListPaneView() to be incorrectly handled or ignored. ( f5fbf3 )
  • The visual state of dialog destinations now correctly stays in sync with the DialogFragmentNavigator 's state. This means that manually calling the asynchronous dismiss() API for DialogFragment now properly clears all dialog destinations above the now dismissed dialog. This does not affect cases where you use popUpTo or popBackStack() to dismiss your dialog. ( I77ba2 )
  • AbstractAppBarOnDestinationChangedListener now has clearer error messaging for onDestinationChanged() . ( Ie742d )

Version 2.4.0-alpha10

29 сентября 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha10 is released. Version 2.4.0-alpha10 contains these commits.

Новые возможности

  • NavController now offers the ability to retrieve a list of all visible NavBackStackEntry instances via the visibleEntries StateFlow ( Ia964e )
  • rememberNavController() now takes a optional set of Navigator instances that will be added to the returned NavController to better support optional Navigators such as those from Accompanist Navigation Material . ( I4619e )

Исправления ошибок

  • Dynamic Navigation will no longer crash when the Activity is recreated. ( Ifa6a3 , b/197942869 )
  • Fixed an issue with the system back button that occurs only after popping back to a composable destination that contains a NavHost . ( 3ed148 , b/195668143 )
  • SafeArgs now generates the arguments for fromBundle() and fromSavedStateHandle() in the proper parameter order. ( I824a8 , b/200059831 )

Version 2.4.0-alpha09

September 15, 2021

androidx.navigation:navigation-*:2.4.0-alpha09 is released. Version 2.4.0-alpha09 contains these commits.

Новые возможности

  • You can now use the clearBackStack() method to clear any state that was saved with popBackStack() or popUpToSaveState . ( I80a0f )
  • You can now pass in a list of arguments and/or deep links to your nested navigation graph's builder and they will automatically be added to the resulting graph. ( I8a470 , b/182545357 )

Изменения API

  • The navArgument Kotlin DSL function is now part of navigation-common instead of navigation-compose . This will require updating imports to continue to use this function. ( I1d095 )

Behavior Changes

  • When generating arguments, Safe Args now puts parameters without default values before those with default values. ( I89709 , b/198493585 )

Исправления ошибок

  • When using Navigation Compose, NavGraphs will only be DESTROYED once all their children are DESTROYED . ( I86552 , b/198741720 )
  • Nullable NavDeepLink arguments no longer require a default value. ( Ia14ef , b/198689811 )
  • Calling setGraph() with a new graph will now also clear any saved back stacks in addition to its previous behavior of popping the back stack. ( I97f96 )
  • Fixed an issue where OnDestinationChangedListener instances and the currentBackStackEntryFlow were not notified when using launchSingleTop . ( Iaaebc )

Обновления зависимости

Version 2.4.0-alpha08

1 сентября 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha08 is released. Version 2.4.0-alpha08 contains these commits.

Новые возможности

  • It is now possible to extend the NavType class to create custom NavTypes. Custom types are supported only when building your navigation graph programmatically, such as via the Navigation Graph Kotlin DSL . ( I78440 , b/196871885 )

Behavior Changes

  • When generating actions, Kotlin code generated from Safe Args now puts arguments without default values before those with default values as parameters. ( Idb697 , b/188855904 )
  • Deep links now verify that all required arguments (those without default values) are present in the Uri . ( #204 , b/185527157 )

Исправления ошибок

  • Using getBackStackEntry and previousBackStackEntry inside composable(), in conjunction with remember() , will no longer cause an exception for no destination being on the back stack. ( I75138 , b/194313238 )
  • Navigation Compose now properly recomposes when changing back stack arguments and using launchSingleTop=true . ( Iebd69 , b/186392337 )
  • There will no longer be an ArrayIndexOutOfBoundsException when calling setGraph with a graph with 13 or 29 destinations. ( I1a9f1 , b/195171984 )
  • The SafeArgs java generator should no longer cause lint warnings when generating Args classes. ( I1a666 , b/185843837 )

External Contribution

  • Thanks ospixd for ensuring that deep links verify that all required arguments (those without default values) are present in the Uri . ( #204 , b/185527157 )

Version 2.4.0-alpha07

18 августа 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha07 is released. Version 2.4.0-alpha07 contains these commits.

Исправления ошибок

  • Navigation Compose now properly saves state after configuration changes and when changing graphs while using the multiple back stack feature. ( If5a3d , b/195141957 )
  • Re-selecting the same tab when using navigation compose with multiple back stacks will no longer result in a blank screen. ( I860dc , b/194925622 )
  • NavHost now observes for changes in the Lifecycle.State of NavBackStackEntry s which means using a NavHost in a fragment now will properly be recomposed as the lifecycle changes instead of resulting in a blank screen. ( I4eb85 , b/195864489 )
  • Fixed an issue where dismissing a DialogFragment would not correctly update the NavController state after recreating your activity (ie, after a configuration change). ( Icd72b )
  • Fixed an issue where popping a dialog destination would not update the NavController's system back button handling, potentially causing the NavController to intercept the back button even though it does not have any back stack to pop. ( If3b34 )
  • Safe-args now automatically generates a toSavedStateHandle method for arguments which can be used to test your ViewModel code. ( If1e2d , b/193353880 )

Version 2.4.0-alpha06

August 4, 2021

androidx.navigation:navigation-*:2.4.0-alpha06 is released. Version 2.4.0-alpha06 contains these commits.

Изменения API

  • The requireSlidingPaneLayout() and requireDetailPaneNavHostFragment() methods on AbstractListDetailFragment have been renamed to getSlidingPaneLayout() and getDetailPaneNavHostFragment() , respectively. ( I34a08 )

Behavior Changes

  • When navigating with animations (like Crossfade ), the new destination's Lifecycle will now only reach the RESUMED when the animation completes. ( If0543 , b/172112072 , b/194301889 )
  • Navigation Compose's NavHost now sets the graph as part of the first composition. ( Ieb7be )

Исправления ошибок

  • Popping the last destination of a navigation graph no longer throws a ClassCastException . ( If0543 , b/172112072 , b/194301889 )
  • Fixed a NullPointerException that would occur when adding a deep link without a Uri and navigating via a route or deep link. ( 938a0c , b/193805425 )
  • Fixed an issue in Navigation Compose where a deep linked NavBackStackEntry would not reach the RESUMED state. ( I192c5 )
  • Fixed an issue where popping a dialog destination would not update the NavController's system back button handling, potentially causing the NavController to intercept the back button even though it does not have any back stack to pop. ( aosp/1782668 )

Version 2.4.0-alpha05

21 июля 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha05 is released. Version 2.4.0-alpha05 contains these commits.

Behavior Changes

  • Navigation Compose's NavHost now always uses Crossfades when navigating through destinations. ( I07049 , b/172112072 )
  • You can now make changes to the graph of a NavHost. Graphs with the same startDestination and destinations in the graph will be considered equal and will not clear the NavController back stack. ( I0b8db , b/175392262 )

Исправления ошибок

  • Fixed a NoSuchElementException when calling popBackStack() from within a LifecycleObserver attached to a NavBackStackEntry caused by reentrant updates to the NavController's state. ( I64621 )
  • AbstractListDetailFragment now allows SlidingPaneLayout to be completely stripped from your APK when AbstractListDetailFragment is not used. ( I611ad )
  • NavGraph and NavDestination now override the equals method so two objects with the same values will be considered equal. ( I166eb , b/175392262 )

Version 2.4.0-alpha04

1 июля 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha04 is released. Version 2.4.0-alpha04 contains these commits.

Новые возможности

  • The navigation-fragment artifact now contains a prebuilt implementation of a two pane layout via the new AbstractListDetailFragment . This fragment uses a SlidingPaneLayout to manage a list pane (which your subclass provides) and a detail pane, which uses a NavHostFragment as its implementation, as seen in our example implementation . ( Iac4be , b/191276636 )
  • The NavHost of the navigation-compose artifact now supports dialog destinations in addition to composable destinations. These dialog destinations will each be shown within a Composable Dialog , floating above the current composable destination. ( I011d0 )
val navController = rememberNavController()
    Scaffold { innerPadding ->
        NavHost(navController, "home", Modifier.padding(innerPadding)) {
            composable("home") {
                // This content fills the area provided to the NavHost
                HomeScreen()
            }
            dialog("detail_dialog") {
                // This content will be automatically added to a Dialog() composable
                // and appear above the HomeScreen or other composable destinations
                DetailDialogContent()
            }
        }
    }

Изменения API

  • The add function in NavigatorState has been renamed to push . All current calls to add() will need to be changed to push(). ( Ie89fc , b/172112072 )
  • Custom Navigator instances can now use the pushWithTransaction and popWithTransition APIs on NavigatorState to push or pop a destination asynchronously. Note that this APIs are not yet used by any of the included navigators. ( Ic4d7c , b/172112072 )

Behavior Changes

  • NavDeepLinkBuilder now adds PendingIntent.FLAG_IMMUTABLE to the PendingIntent returned by createPendingIntent() , ensuring that this API works as expected when targeting Android 12. ( If8c52 )

Исправления ошибок

  • Fixed an issue with <include-dynamic> where arguments passed to the graph would not be correctly passed to the dynamically included graph. ( I3e115 )
  • Fixed a NullPointerException when navigating to a destination using a string[] argument with a default value of @null . ( I1fbe8 )
  • Add ProGuard rules for @Navigator.Name , fixing issues when using R8 3.1 full mode. ( I2add9 , b/191654433 )
  • SafeArgs will no longer fail when building your app with Kotlin versions before 1.5.0 . ( Icd1ff , b/190739257 )

Версия 2.4.0-альфа03

16 июня 2021 г.

androidx.navigation:navigation-*:2.4.0-alpha03 is released. Версия 2.4.0-alpha03 содержит эти коммиты.

Исправления ошибок

  • Fixed an issue where two navigate() calls were needed to navigate to an included dynamic graph. ( I7785c , b/188859835 )
  • Fixed a regression introduced in Navigation 2.4.0-alpha01 where setupActionBarWithNavController() would not properly remove the Up icon when you are on a top level destination. ( I5d443 , b/189868637 )
  • Fixed an IllegalStateException when calling popBackStack() after previously popping the root graph of the NavController. ( I2a330 , b/190265699 )
  • ProGuard rules for by navArgs() now properly apply when using navigation-common or any artifacts that depend on it. ( I68800 , b/190082521 )
  • An OnDestinationChangedListener that calls navigate() the first time it receives a callback now properly get a second callback with the destination it navigated to. ( Ie5f9e , b/190228815 )
  • Safe Args no longer crashes when using it with dynamic feature modules and AGP 7.0+. ( I69518 , b/189966576 )

Известная проблема

  • Safe Args will fail with an Unable to find method ''java.lang.String kotlin.text.CarsKt.titleCase(char, java.util.Locale)'' error when using Gradle 6.7.0 due to a dependency on an older version of Kotlin. This can be worked around by updating to use Gradle 7.0. ( b/190739257 )

Версия 2.4.0-альфа02

2 июня 2021 года

androidx.navigation:navigation-*:2.4.0-alpha02 is released. Версия 2.4.0-alpha02 содержит эти коммиты.

Новые возможности

  • Routes are now supported for Activity, Fragment and Dialog destinations, as well as throughout the DynamicNavigation Kotlin DSL. ( Ib5544 , Ia617b , I22f96 , b/188914648 , b/188901565 )
  • NavigationUI has temporarily added experimental APIs to allow opting out of saving your state. While always saving the state is the correct behavior, there are still uses of deprecated libraries (ie retained fragments), that cannot be supported when saving the state so this gives an opportunity for apps to slowly convert away from any unsupported APIs. ( Idf93c )
  • Navigation now provides findDestination() and getHierarchy() APIs that can be used to help implement custom NavigationUI. findDestination() is an extension function on NavGraph that will locate a destination within the graph. getHierarchy() is a function on NavDestination that can be used to verify if a given destination is within the hierarchy of another.( I2932f , b/188183365 )

    val matchingRoute: Boolean = destination.hierarchy.any { it.route == routeToFind }
    
  • NavigationUI methods that took a BottomNavigationView have been updated to instead take its superclass introduced in Material 1.4.0 , NavigationBarView . This allows these methods to be used with the NavigationRailView . ( Ib0b36 , b/182938895 )

  • When inflating an <action> element via XML, animation attributes can use attributes pulled from your theme using the app:enterAnim="?attr/transitionEnter" syntax. ( I07bc1 , b/178291654 )

Изменения API

Исправления ошибок

  • DialogFragmentNavigator now uses the NavigatorState.pop() API to inform the NavController when a dialog is dismissed by hitting the system back button or clicking outside of it, ensuring that the NavController state is always in sync with the Navigator's state. ( I2ead9 )
  • Navigation no longer gives a ConcurrentModificationException when using manipulating the list of OnDestinationChangedListeners from with an onDestinationChanged callback. ( Ib1707 , b/188860458 )

  • Safe Args no longer crashes when attempting to generate direction properties in Kotlin. ( Id2416 , b/188564435 )

  • The setId method on NavDestination is now properly annotated with @IdRes , so it only accepts resource ids. ( I69b80 )

  • The int parameter of findNode is now resId instead of resid . ( I7711d )

Dependency Update

  • Safe-Args now depends on Android Gradle Plugin 4.2.0. This means you should no longer get the using applicationIdTextResource warning. ( I6d67b , b/172824579 )

Версия 2.4.0-альфа01

May 18, 2021

androidx.navigation:navigation-*:2.4.0-alpha01 is released. Версия 2.4.0-alpha01 содержит эти коммиты.

Новые возможности

  • The currentBackStackEntryAsFlow() method on NavController provides a Flow that emits whenever the current NavBackStackEntry changes. This flow can be used as an alternative to manually managing an OnDestinationChangedListener . ( I19c4a , #89 , b/163947280 )

Multiple back stacks

The NavController is responsible for managing the back stack of destinations, adding destinations to the back stack when you navigate() to them and removing them when you call popBackStack() or trigger the system back button. The existing NavOptions class and the integration into <action> entries in the navigation graph XML has been expanded to support saving and restoring the back stack. ( b/80029773 )

As part of this change, the NavigationUI methods of onNavDestinationSelected() , BottomNavigationView.setupWithNavController() and NavigationView.setupWithNavController() now automatically save and restore the state of popped destinations, enabling support for multiple back stacks without any code changes. When using Navigation with Fragments, this is the recommended way to integrate with multiple back stacks. ( Ie07ca )

The underlying APIs for saving and restoring the state are exposed via a number of surfaces:

  • In Navigation XML, the <action> element can now use the boolean attributes of app:popUpToSaveState and app:restoreState to save the state of any destinations popped via app:popUpTo and restore the state associated with the destination passed as the app:destination :

    <action
      android:id=”@+id/swap_stack”
      app:destination=”@id/second_stack”
      app:restoreState=”true”
      app:popUpTo=”@id/first_stack_start_destination”
      app:popUpToSaveState=”true” />
    
  • In the navOptions Kotlin DSL , you can add the restoreState boolean property and the saveState boolean property on the popUpTo builder :

    // Use the navigate() method that takes a navOptions DSL Builder
    navController.navigate(selectedBottomNavRoute) {
      launchSingleTop = true
      restoreState = true
      popUpTo(navController.graph.startDestinationId) {
        saveState = true
      }
    }
    
  • In manually building a NavOptions object via the NavOptions.Builder , you can use the setRestoreState() and new overload to setPopUpTo() that takes an additional saveState parameter.

    NavOptions navOptions = new NavOptions.Builder()
      .setLaunchSingleTop(true)
      .setRestoreState(true)
      .setPopUpTo(navController.getGraph().getStartDestinationId(),
        false, // inclusive
        true) // saveState
      .build();
    navController.navigate(selectedBottomNavId, null, navOptions);
    
  • Programmatic calls to popBackStack() can now include an additional saveState parameter.

In all cases, the NavController will save and restore the state of each NavBackStackEntry , including any navigation destination scoped ViewModel instances. The Navigator APIs have been updated to enable each Navigator to support saving and restoring their own state.

The ComposeNavigator used for composable destinations in Navigation Compose and the FragmentNavigator and DynamicFragmentNavigator used for <fragment> destinations in Navigation with Fragments have both been updated to use the new Navigator APIs and support saving and restoring state.

Navigation Routes

A route is a String that uniquely identifies a destination. While previously only used in Navigation Compose , this concept has now graduated to become a part of the core Navigation APIs. This provides an alternative to using integer IDs when constructing your graph through the Navigation Kotlin DSL . ( b/172823546 )

All APIs that used to only take an ID now have an overload that takes a route String . This includes navigate() , popBackStack() , popUpTo() , and getBackStackEntry() .

This has had some API implications:

  • The popUpTo kotlin property on the Kotlin DSL has been deprecated in favor of popUpToId . ( I59c73 , b/172823546 )
  • The getStartDestination() API has been deprecated in favor of getStartDestinationId() . ( I0887f , b/172823546 )

For developers upgrading from previous versions of Navigation Compose to Navigation Compose 2.4.0-alpha01 , this means that the following imports on extension methods are no longer necessary and should be removed:

import androidx.navigation.compose.navigation
import androidx.navigation.compose.createGraph
import androidx.navigation.compose.getBackStackEntry
import androidx.navigation.compose.navigate
import androidx.navigation.compose.popUpTo

The KEY_ROUTE argument has been replaced with the route property on NavDestination , allowing you to call navBackStackEntry.destination.route directly.

Изменения API

  • All Navigation artifacts have been rewritten in Kotlin. This has improved the nullability of classes using generics (such as NavType subclasses). All Kotlin extension functions that used to be part of the -ktx artifacts have been moved to their respective main artifacts. The -ktx artifacts will continue to be published, but are completely empty. ( b/184292145 )
  • NavDeepLinkBuilder now supports adding multiple distinct destinations to the generated back stack. ( I3ee0d , b/147913689 )
  • Add factory functions for DynamicNavHostFragment ( Icd515 , b/175222619 )
  • The unique ID of a NavBackStackEntry is now exposed as part of its public API. ( Ie033a )
  • The name and argument fields and destructuring functions of NamedNavArgument are now public. ( #174 , b/181320559 )
  • Introduced a new NavBackStackEntry#provideToCompositionLocals extension that provides the NavBackStackEntry to the relevant composition locals. ( #175 , b/187229439 )

Safe Args

  • Safe Args now generates a fromSavedStateHandle() method for each NavArgs class. ( #122 , b/136967621 )

    class HomeViewModel(savedStateHandle: SavedStateHandle) : ViewModel() {
      // Create a HomeDestinationArgs class with type safe accessors for each argument
      // defined on your destination
      private val args = HomeDestinationArgs.fromSavedStateHandle(savedStateHandle)
    }
    
  • Updated Safe Args to depend on KotlinPoet 1.8.0 . ( #172 , b/183990444 )

Behavior Changes

  • Navigation now depends on Lifecycle 2.3.1 and now marks setGraph() , popBackStack() , navigateUp() , and navigate() , the methods that update the NavBackStackEntry Lifecycle , as @MainThread , aligning Navigation with the main thread enforcement introduced in Lifecycle 2.3.0 . ( b/171125856 )
  • Parsing Enum arguments from deep links is now case insensitive, allowing a deep link like http://www.example.com/red to match a www.example.com/{color} deep link even when the enum has the value of RED . ( #152 , b/135857840 )

Compose Compatibility

  • androidx.navigation:navigation-compose:2.4.0-alpha01 is only compatible with Compose version 1.0.0-beta07 and above.

Исправления ошибок

  • Fixed an issue where trailing argument placeholders would take precedence over deep links that have a matching exact suffix. ( #153 , b/184072811 )
  • NavHostFragment now supports custom Navigators that use the same @Navigator.Name("dialog") as the default DialogFragmentNavigator . ( Ib1c2c , b/175979140 )
  • Improved the behavior of NavigatorProvider#addNavigator to ensure that calling it repeatedly with the same instance does not cause issues. ( #176 , b/187443146 )

External Contributions

  • Thanks simonschiller for building support for Safe Args generating a fromSavedStateHandle() method for each NavArgs class. ( #122 , b/136967621 )
  • Thanks Bradleycorn for making parsing Enum arguments from deep links case insensitive. ( #152 , b/135857840 )
  • Thanks osipxd for fixing an issue where trailing argument placeholders would take precedence over deep links that have a matching exact suffix. ( #153 , b/184072811 )
  • Thanks tatocaster for updating Safe Args to depend on KotlinPoet 1.8.0 . ( #172 , b/183990444 )
  • Thanks jossiwolf for making the name and argument fields and destructuring functions of NamedNavArgument public. ( #174 , b/181320559 )
  • Thanks jossiwolf for introducing a new NavBackStackEntry#provideToCompositionLocals extension that provides the NavBackStackEntry to the relevant composition locals. ( #175 , b/187229439 )
  • Thanks jossiwolf for improved the behavior of NavigatorProvider#addNavigator to ensure that calling it repeatedly with the same instance does not cause issues. ( #176 , b/187443146 )

Версия 1.0.0-Alpha10

7 апреля 2021 г.

androidx.navigation:navigation-compose:1.0.0-alpha10 is released. Версия 1.0.0-Alpha10 содержит эти коммиты.

Изменения API

  • NavHost now accepts a Modifier , which is passed down to the composable container that wraps the destination composables. ( I85aca , b/175125483 )

Исправления ошибок

  • NavHost now works even when an OnBackPressedDispatcherOwner is not found, such is the case when previewing the NavHost . ( I7d8b4 )
  • Navigation Compose now depends on Navigation 2.3.5 , fixing an issue when using BackHandler inside a NavHost destination. ( I7e63b , b/182284739 )

Версия 1.0.0-Alpha09

10 марта 2021 г.

androidx.navigation:navigation-compose:1.0.0-alpha09 is released. Версия 1.0.0-Alpha09 содержит эти коммиты.

Изменения API

  • LocalViewModelStoreOwner.current now returns a nullable ViewModelStoreOwner to better determine whether a ViewModelStoreOwner is available in the current composition. APIs that require a ViewModelStoreOwner , such as viewModel() and NavHost , still throw an exception if a ViewModelStoreOwner is not set. ( Idf39a )

Исправления ошибок

  • Navigation Compose now depends on Navigation 2.3.4 which includes the fix for attempting to set the same ViewModelStore object after the graph has been set. ( I65c24 , b/177825470 )

Версия 1.0.0-альфа08

24 февраля 2021 года

androidx.navigation:navigation-compose:1.0.0-alpha08 is released. Версия 1.0.0-Alpha08 содержит эти коммиты.

Новые возможности

  • NavHost now populates the LocalSavedStateRegistryOwner CompositionLocal with that destination's NavBackStackEntry , ensuring that any state directly saved into the SavedStateRegistry will be saved and restored alongside the destination. ( I435d7 , b/179469431 )

Версия 1.0.0-альфа07

10 февраля 2021 г.

androidx.navigation:navigation-compose:1.0.0-alpha07 is released. Версия 1.0.0-Alpha07 содержит эти коммиты.

Обновления зависимости

Версия 1.0.0-альфа06

28 января 2021 г.

androidx.navigation:navigation-compose:1.0.0-alpha06 is released. Версия 1.0.0-Alpha06 содержит эти коммиты.

Изменения API

  • Added a getBackStackEntry(route: String) extension method on NavController that returns the associated NavBackStackEntry . ( If8931 )

Версия 1.0.0-альфа05

January 13, 2021

androidx.navigation:navigation-compose:1.0.0-alpha05 is released. Версия 1.0.0-Alpha05 содержит эти коммиты.

Updated to depend on Compose 1.0.0-alpha10.

Версия 1.0.0-альфа04

December 16, 2020

androidx.navigation:navigation-compose:1.0.0-alpha04 is released. Версия 1.0.0-Alpha04 содержит эти коммиты.

  • Updated for compatibility with Compose 1.0.0-alpha09 .

Версия 1.0.0-альфа03

December 2, 2020

androidx.navigation:navigation-compose:1.0.0-alpha03 is released. Версия 1.0.0-Alpha03 содержит эти коммиты.

Исправления ошибок

  • Fixed an issue where popBackStack() and navigateUp() would not work after a configuration change or process death and recreation. ( Icea47 , b/173281473 )
  • Navigating to a nested graph within your NavHost now works properly. ( I0948d , b/173647694 )

Версия 1.0.0-альфа02

11 ноября 2020 г.

androidx.navigation:navigation-compose:1.0.0-alpha02 is released. Версия 1.0.0-Alpha02 содержит эти коммиты.

Изменения API

  • Navigation compose now support NavOptions for using popUpTo and launchSingleTop operations ( If96c3 , b/171468994 )
  • Added a navigation function that takes a route instead of an ID that allows you to construct nested graphs in the Navigation Compose DSL. ( I1661d )
  • startDestination now comes before the route in the list of a parameters for a NavHost ( Ie620e )
  • You can now create a graph using the route as a start destination outside of a NavHost composable. ( Iceb75 )

Версия 1.0.0-альфа01

28 октября 2020 г.

android.navigation:navigation-compose:1.0.0-alpha01 is released. Версия 1.0.0-Alpha01 содержит эти коммиты.

Новые возможности

The navigation-compose artifact provides integration between the Navigation Component and Jetpack Compose . It uses @Composable functions as the destinations in your application.

This initial release provides:

  • A NavHost composable that allows you to construct your navigation graph via a Kotlin DSL.
  • Scoping of lifecycle, ViewModel , and remembered state at the destination level.
  • Automatic integration with the system back button.
  • Support for passing arguments, attaching deep links to destinations, and returning a result to previous destinations.
  • Compose specific helpers in rememberNavController() and currentBackStackEntryAsState() to allow hoisting state and connecting the NavController to composables outside of the NavHost (such as a bottom navigation bar).

See the Compose Navigation guide for more information.

Version 2.3.5

Version 2.3.5

7 апреля 2021 г.

androidx.navigation:navigation-*:2.3.5 is released. Version 2.3.5 contains these commits.

Новые возможности

  • When navigating using a NavDeepLinkRequest or Uri , you can now access the Uri , action, and mime type in the resulting destination by getting the intent from arguments via KEY_DEEP_LINK_INTENT , mirroring the functionality already available for external deep linking. ( I975c3 , b/181521877 )

Исправления ошибок

  • OnBackPressedCallbacks added to a dispatcher with the NavBackStackEntry as the LifecycleOwner now properly intercept back after the Activity Lifecycle is STOPPED , then STARTED ( Iff94f , b/182284739 )
  • Deep link domain parsing is now case insensitive, ensuring that www.example.com matches both www.example.com and www.Example.com . Note that query parameter names are still case sensitive. ( #144 , b/153829033 )
  • Fixed a NullPointerException that could occur when a destination has multiple non-nullable default arguments and you navigate to that destination while only overriding a subset of those arguments. ( aosp/1644827 )

Обновления зависимости

External Contribution

Version 2.3.4

Version 2.3.4

10 марта 2021 г.

androidx.navigation:navigation-*:2.3.4 is released. Version 2.3.4 contains these commits.

Новые возможности

  • ReferenceType arguments can now be properly parsed when sent as part of a deeplink URI. This supports both the raw integer value as well as hex values prefixed by 0x . ( #127 , b/179166693 )
  • The android:defaultValue for an argument with app:argType="float" now supports integer default values, allowing you to use android:defaultValue="0" rather than requiring the use of 0.0 . ( #117 , b/173766247 )

Исправления ошибок

  • Fix stuck installation progress when using Navigation's support for dynamic features. ( Ib27a7 , b/169636207 )
  • Calling setViewModelStore or setLifecycleOwner with the same object that has already been set will now be a no-op ( Idf491 , b/177825470 )
  • Safe-Args now adds suppress annotations on the proper methods when using java. ( I8fbc5 , b/179463137 )

External Contributions

  • Thanks JvmName for the pull request to ensure that ReferenceType arguments can now be properly parsed when sent as part of a deeplink URI. ( #127 , b/179166693 )
  • Thanks tatocaster for the pull request to allow the defaultValue for an argument with app:argType=”float” now supports integer default values. ( #117 , b/173766247 )

Version 2.3.3

Version 2.3.3

27 января 2021 г.

androidx.navigation:navigation-*:2.3.3 is released. Version 2.3.3 contains these commits.

Исправления ошибок

  • There is no longer a crash when popping a NavBackStackEntry before its Lifecycle is moved to CREATED . ( Ie3ba3 )
  • Fixed regression caused by b/171364502 where navigating to an activity with an animation resource value of 0 caused a ResourceNotFoundException . ( I7aedb , b/176819931 )

Version 2.3.2

Version 2.3.2

December 2, 2020

androidx.navigation:navigation-*:2.3.2 is released. Version 2.3.2 contains these commits.

Исправления ошибок

  • Fixed a regression in NavigationUI where using an <activity> destination with onNavDestinationSelected would fail to navigate to the Activity. ( I22e34 , b/171364502 )
  • Fixed an issue where navigation-dynamic-features-fragment would result in navigating to the newly installed destination multiple times. ( aosp/1486056 , b/169636207 )
  • Fixed an issue where default arguments would not be sent to OnDestinationChangedListener instances when using launchSingleTop . ( I2c5cb )
  • Fixed an issue where navigating to a nested navigation graph would not create a new graph instance on the back stack. ( Ifc831 )
  • Fixed an issue where using navigate() with a popUpTo that removed the last destination in a navigation graph would not immediately destroy and remove the navigation graph itself from the back stack. ( I910a3 )
  • Navigation SafeArgs now uses KotlinPoet version 1.7.2 which adds support for Kotlin's explicit API mode. ( I918b5 )
  • NavHostFragment.findNavController(Fragment) now also checks the root decor view of a DialogFragment in addition to the existing checks of the Fragment hierarchy and Fragment's view hierarchy. This allows you to test dialog fragments that use Navigation with FragmentScenario and Navigation.setViewNavController() . ( I69e0d )

Версия 2.3.1

Версия 2.3.1

14 октября 2020 г.

androidx.navigation:navigation-*:2.3.1 is released. Версия 2.3.1 содержит эти коммиты.

Новые возможности

  • Default Animator resources have been added to Navigation UI and are recommended over the default animation resources. ( b/167430145 )
  • NavOptions now overrides the hashcode and equals methods ( b/161586466 )
  • Navigation now includes the current destination in the “No destination with ID” IllegalArgumentException, which should improve the developer debugging experience. ( b/168311416 )

Исправления ошибок

  • Safe Args will no longer wrap the return line, even if the generated argument class name is longer than 100 characters. ( b/168584987 )

Dependency Changes

  • navigation-ui now depends on DrawerLayout 1.1.1 , ensuring that NavigationUI is able to open the drawer even when using LOCK_MODE_LOCKED_CLOSED or LOCK_MODE_LOCKED_OPEN . ( b/162253907 )
  • Safe Args now depends on KotlinPoet 1.6.0 ( aosp/1435911 )
  • Safe Args now depends on AGP 4.0.1 ( aosp/1442337 )

Версия 2.3.0

Версия 2.3.0

June 24, 2020

androidx.navigation:navigation-*:2.3.0 is released. Версия 2.3.0 содержит эти коммиты.

Major changes since 2.2.0

  • Feature Module integration : The navigation-dynamic-features-runtime and navigation-dynamic-features-fragment artifacts allow you to navigate to destinations that are defined in feature modules, automatically handling the installation of the feature modules as needed. See Navigate with feature modules for more information.
  • Navigation Testing : The navigation-testing artifact provides a TestNavHostController that allows you to set the current destination and verify the back stack after navigation operations. See Test Navigation for more information.
  • Returning a Result : The NavBackStackEntry associated with each destination on the Navigation back stack now allows you to access a SavedStateHandle suitable for storing small amounts of saved state that should be associated with a particular back stack entry. See Returning a result to the previous Destination for more information.
  • NavigationUI support for Openable : All usages of DrawerLayout in NavigationUI have been replaced with the more generic Openable interface added in CustomView 1.1.0 and implemented by DrawerLayout in DrawerLayout 1.1.0 .
  • Action and Mime Type support in deep links : Deep linking has been expanded to support app:action and app:mimeType in addition to the app:uri previously available. NavController now supports navigating by any combination of these fields via the new NavDeepLinkRequest class. See Navigate using NavDeepLinkRequest for more information.

Известные проблемы

  • Support for deep link actions and mime types is not yet available in Manifest Merger . Until that work is completed, any generated <intent-filter> elements from the <nav-graph> element in your manifest won't include your mime type in its <data> element or your custom <action> . You must manually add an appropriate <intent-filter> to your manifest.

Версия 2.3.0-rc01

June 10, 2020

androidx.navigation:navigation-*:2.3.0-rc01 is released. Версия 2.3.0-rc01 содержит эти коммиты.

Исправления ошибок

  • Fixed a NullPointerException when replacing an instance of a destination with no arguments with another instance with arguments with singleTop . ( b/158006669 )
  • All destination is unknown exceptions thrown by NavController now have additional debugging information to help determine the state of the NavController . ( b/157764916 )

Версия 2.3.0-бета01

20 мая 2020 г.

androidx.navigation:navigation-*:2.3.0-beta01 are released. Версия 2.3.0-beta01 содержит эти коммиты.

Исправления ошибок

  • Fixed an issue where the Lifecycle of the NavBackStackEntry would not be properly updated after process death. ( b/155218371 )
  • OnDestinationChangedListener instances registered before calling setGraph() are now properly sent the restored destination after a process death. ( b/155218371 )
  • When using singleTop , the NavBackStackEntry now correctly has its arguments updated and the updated arguments are sent to all OnDestinationChangeListener instances. ( b/156545508 )

Обновления зависимости

Version 2.3.0-alpha06

April 29, 2020

androidx.navigation:navigation-*:2.3.0-alpha06 is released. ( Version 2.3.0-alpha06 contains these commits. )

Новые возможности

  • Deep linking has been expanded to support app:action and app:mimeType in addition to the app:uri previously available. NavController now supports navigating by any combination of these fields via the new NavDeepLinkRequest class. ( b/136573074 , b/135334841 )

Изменения API

  • Greatly expanded the Kotlin DSL support for Dynamic Navigation destinations. ( b/148969800 )

Исправления ошибок

  • Fixed an issue where deep link Intents would be ignored when using a nested start destination. ( b/154532067 )

Версия 2.3.0-альфа05

15 апреля 2020 г.

androidx.navigation:navigation-*:2.3.0-alpha05 is released. Версия 2.3.0-alpha05 содержит эти коммиты.

Новые возможности

  • For dynamic graph includes using <include-dynamic> , you no longer need to specify app:graphPackage and a default one will be used by adding moduleName suffix to the applicationId after a dot. If you do need to customize your graphPackage , an ${applicationId} placeholder is now supported. ( b/152696768 )
  • The Navigation Graph Kotlin DSL now exposes a defaultArguments Map for actions, mirroring the ability to set default values on <action> elements in Navigation XML files. ( b/150345605 )

Исправления ошибок

  • From Navigation 2.2.2 : Fixed an IllegalStateException when deep linking to the start destination of your graph when you have multiple NavHostFragment instances in your Activity. ( b/147378752 )

Обновления зависимостей

Версия 2.3.0-альфа04

18 марта 2020 г.

androidx.navigation:navigation-*:2.3.0-alpha04 is released. Версия 2.3.0-alpha04 содержит эти коммиты.

Новые возможности

  • Added support for feature module activity and fragment destinations in the Navigation Kotlin DSL. ( b/148969800 )

Изменения API

  • The DynamicExtras class no longer uses a builder pattern and can now be constructed directly. ( aosp/1253671 )
  • DynamicActivityNavigator now takes a Context in its constructor rather than an Activity . ( aosp/1250252 )

Исправления ошибок

  • NavigationUI no longer ignores empty labels (ie, a destination with android:label=”” ) and now correctly sets the title to an empty string. ( b/148679860 )

Обновления зависимости

  • The Navigation Dynamic Features artifacts now depend on Play Core 1.6.5 . ( b/149556401 )

Версия 2.3.0-альфа03

March 4, 2020

androidx.navigation:navigation-*:2.3.0-alpha03 is released. Версия 2.3.0-alpha03 содержит эти коммиты.

Изменения API

Исправления ошибок

  • The navigation-common-ktx ProGuard rules now correctly only keep the NavArgs classes that are used rather than all NavArgs instances. ( b/150213558 )

Dependency changes

  • Navigation has reverted its dependency on Core 1.2.0 and now depends on Core 1.1.0 to avoid forcing developers to move to a newer dependency when Navigation does not depend on any new APIs in Core 1.2.0 .

Версия 2.3.0-альфа02

19 февраля 2020 г.

androidx.navigation:navigation-*:2.3.0-alpha02 is released. Версия 2.3.0-alpha02 содержит эти коммиты.

Новые возможности

  • The NavBackStackEntry now allows you to access a SavedStateHandle suitable for storing small amounts of saved state that should be associated with a particular back stack entry. See Returning a result for an example use case. ( b/79672220 )

Изменения API

  • Convenience methods of getCurrentBackStackEntry() and getPreviousBackStackEntry() have been added to make it easier to retrieve a NavBackStackEntry for the current and previous destinations. ( b/79672220 )

Исправления ошибок

  • navigateUp() now passes the current destination's arguments and the KEY_DEEP_LINK_INTENT to the previous destination when launching your app on your own task stack. ( b/147456890 )

Dependency changes

Версия 2.3.0-альфа01

5 февраля 2020 года

androidx.navigation:navigation-*:2.3.0-alpha01 is released. Version 2.3.0-alpha01 contains these commits .

Новые функции

  • The new navigation-testing artifact provides a TestNavHostController class. This class provides an alternative to using a mock NavController when testing Navigation that allows you to set the current destination and verify the back stack after navigation operations. ( b/140884273 )
  • The new navigation-dynamic-features-fragment (and its transitive dependency, navigation-dynamic-features-runtime ) allows you to include destinations or entire navigation graphs (via <include-dynamic> ) from feature modules , providing seamless installation of on-demand feature modules when navigating to those destinations. See Navigate with feature modules for more information. ( b/132170186 )

Исправления ошибок

  • From Navigation 2.2.1 : Deep links without query parameters now correctly ignore any query parameters rather than appending them to trailing {argument} elements or not matching the deep link. ( b/147447512 )
  • From Navigation 2.2.1 : The navigation-ui ProGuard rules for DrawerArrowDrawable have been updated to ensure that android.enableJetifier=true is not required. ( b/147610424 )
  • From Navigation 2.2.1 : The navigation-common-ktx module now has a unique manifest package name instead of sharing the same manifest package name as navigation-runtime-ktx . ( aosp/1141947 )

Обновления зависимостей

Version 2.2.2

Version 2.2.2

15 апреля 2020 г.

androidx.navigation:navigation-*:2.2.2 are released. Version 2.2.2 contains these commits.

Исправления ошибок

  • Fixed an IllegalStateException when deep linking to the start destination of your graph when you have multiple NavHostFragment instances in your Activity. ( b/147378752 )
  • NavigationUI no longer ignores empty labels (ie, a destination with android:label=”” ) and now correctly sets the title to an empty string. This was previously released in Navigation 2.3.0-alpha04 . ( b/148679860 )
  • The navigation-common-ktx ProGuard rules now correctly only keep the NavArgs classes that are used rather than all NavArgs instances. This was previously released in Navigation 2.3.0-alpha03 . ( b/150213558

Обновления зависимостей

Версия 2.2.1

Версия 2.2.1

5 февраля 2020 года

androidx.navigation:navigation-*:2.2.1 is released. Version 2.2.1 contains these commits .

Исправления ошибок

  • Deep links without query parameters now correctly ignore any query parameters rather than appending them to trailing {argument} elements or not matching the deep link. ( b/147447512 )
  • The navigation-ui ProGuard rules for DrawerArrowDrawable have been updated to ensure that android.enableJetifier=true is not required. ( b/147610424 )
  • The navigation-common-ktx module now has a unique manifest package name instead of sharing the same manifest package name as navigation-runtime-ktx . ( aosp/1141947 )

Обновления зависимостей

Версия 2.2.0

Версия 2.2.0

22 января 2020 г.

androidx.navigation:navigation-*:2.2.0 is released. Version 2.2.0 contains these commits .

Важные изменения с версии 2.1.0

  • NavBackStackEntry : You can now call NavController.getBackStackEntry() , passing in the ID of a destination or navigation graph on the back stack. The returned NavBackStackEntry provides a Navigation-driven LifecycleOwner , ViewModelStoreOwner (the same returned by NavController.getViewModelStoreOwner() ), and SavedStateRegistryOwner , in addition to providing the arguments used to start that destination.
  • Lifecycle ViewModel SavedState Integration : SavedStateViewModelFactory is now the default factory used when using by navGraphViewModels() or the ViewModelProvider constructor with a ViewModelStoreOwner returned by NavController.getBackStackEntry() or NavController.getViewModelStoreOwner() .
  • Query Parameter Support for Deep Links : Deep links with query parameters now support reordered query parameters; arguments that have a default value or are nullable are now optional when matching deep links.
  • Improved Animation Support : NavHostFragment now uses FragmentContainerView from Fragment 1.2.0 , fixing animation z-ordering issues and window insets dispatching to Fragments.

Version 2.2.0-rc04

18 декабря 2019 г.

androidx.navigation:navigation-*:2.2.0-rc04 is released. Version 2.2.0-rc04 contains these commits .

Исправления ошибок

Version 2.2.0-rc03

4 декабря 2019 г.

androidx.navigation:navigation-*:2.2.0-rc03 is released. Version 2.2.0-rc03 contains these commits .

Исправления ошибок

  • Fixed an issue with deep link parsing when using query parameters and an argument as the last part of the path that prevented more than one character of the final path argument from being parsed. ( b/144554689 )
  • Fixed an issue with deep link parsing where optional parameters would receive "@null" instead of null . ( b/141613546 )
  • NavHostFragment now correctly restores the graph after a configuration change when used with FragmentContainerView . ( b/143752103 )

Dependency changes

  • Navigation now depends on Lifecycle 2.2.0-rc03 , Lifecycle ViewModel SavedState 1.0.0-rc03 , Activity 1.1.0-rc03 , and Fragment 1.2.0-rc03 where appropriate.

Version 2.2.0-rc02

7 ноября 2019 г.

androidx.navigation:navigation-*:2.2.0-rc02 is released. Version 2.2.0-rc02 contains these commits .

Dependency changes

  • Navigation now depends on androidx.lifecycle 2.2.0-rc02 .

Версия 2.2.0-rc01

23 октября 2019 года

androidx.navigation:navigation-*:2.2.0-rc01 is released with no changes since 2.2.0-beta01 . Version 2.2.0-rc01 contains these commits .

Версия 2.2.0-бета01

9 октября 2019 года

androidx.navigation:navigation-*:2.2.0-beta01 is released. Version 2.2.0-beta01 contains these commits .

Новые функции

  • NavDestination and its subclasses now override toString() to provide more helpful information when debugging. ( b/141264986 )

Изменения в поведении

  • Extra query parameters are now ignored when matching deep links rather than causing the match to fail. ( b/141482822 )

Исправления ошибок

  • Fixed an issue where arguments in a deep link's path would be ignored if query parameters were also specified. ( b/141505755 )
  • The navArgs() Kotlin extension on Activity now has a better error message when there are no extras. ( b/141408999 )
  • Safe Args generated Directions Java classes now contain default values. ( b/141099045 )
  • Safe Args generated Args Java classes now contain default values. ( b/140123727 )
  • When using a Toolbar , NavigationUI no longer animates the text change when moving between two top level destinations. ( b/140848160 )

Version 2.2.0-alpha03

September 18, 2019

androidx.navigation:navigation-*:2.2.0-alpha03 is released. Version 2.2.0-alpha03 contains these commits .

Изменения в поведении

  • Calling setViewModelStore() after calling setGraph now results in an IllegalStateException . This should always be set by the NavHost as part of the initial setup to ensure that all NavBackStackEntry instances have a consistent storage for ViewModel instances. ( aosp/1111821 )

Исправления ошибок

  • Fixed a ConcurrentModificationException when using ViewModel instances attached to multiple different navigation graph scoped ViewModelStore instances. ( aosp/1112257 )

Версия 2.2.0-альфа02

September 5, 2019

androidx.navigation:navigation-*:2.2.0-alpha02 is released. The commits included in this version can be found here .

Новые функции

  • Deep links with query parameters now support reordered query parameters; arguments that have a default value or are nullable are now optional when matching deep links. ( b/133273839 )
  • You can now call NavController.getBackStackEntry() , passing in the ID of a destination or navigation graph on the back stack. The returned NavBackStackEntry provides a Navigation-driven LifecycleOwner , ViewModelStoreOwner (the same returned by NavController.getViewModelStoreOwner() ), and SavedStateRegistryOwner , in addition to providing the arguments used to start that destination. ( aosp/1101691 , aosp/1101710 )

Исправления ошибок

  • Fixed an issue where adding a NavHostFragment to ViewPager2 failed with an IllegalArgumentException . ( b/133640271 )
  • NavInflater now avoids calling getResourceName() unnecessarily, speeding up inflation time by up to 40%. ( b/139213740 )

Версия 2.2.0-альфа01

August 7, 2019

androidx.navigation:navigation-*:2.2.0-alpha01 is released. The commits included in this version can be found here .

Новые функции

  • SavedStateViewModelFactory is now the default factory used when using by navGraphViewModels() or the ViewModelProvider constructor with a ViewModelStoreOwner returned by NavController.getViewModelStoreOwner() . ( b/135716331 )

Изменения API

Исправления ошибок

  • NavHostFragment now uses FragmentContainerView , fixing animation z-ordering issues and window insets dispatching to Fragments. ( b/137310379 )

Версия 2.1.0

Версия 2.1.0

September 5, 2019

androidx.navigation:navigation-*:2.1.0 is released. The commits included in this version can be found here .

Important changes since 2.0.0

  • Scoping ViewModels to a navigation graph : You can now create ViewModels that are scoped at the navigation graph level using the by navGraphViewModels() property delegate for Kotlin users using the -ktx libraries or by using the getViewModelStoreOwner() API added to NavController . See Share UI-related data between destinations for more information.
  • Dialog destinations : You can now create <dialog> destinations that will show a DialogFragment when you navigate to them. NavHostFragment supports dialog destinations by default. See Create a destination from a DialogFragment for more information.
  • Navigating by Uri : You can now navigate using a Uri , which uses the <deepLink> you've added to a destination to navigate there. See Navigate using Uri for more information.
  • NavHostController : APIs used specifically for constructing a custom NavHost have been moved to NavHostController , allowing implementations to connect their NavController to the hosting LifecycleOwner , OnBackPressedDispatcher , and ViewModelStore .

Версия 2.1.0-rc01

August 7, 2019

androidx.navigation:navigation-*:2.1.0-rc01 is released. The commits included in this version can be found here .

Изменения API

  • The deprecated getViewModelStore() API on NavController introduced in 2.1.0-alpha02 has been removed. ( aosp/1091021 )

Version 2.1.0-beta02

July 19, 2019

androidx.navigation:*:2.1.0-beta02 is released. The commits included in this version can be found here .

Исправления ошибок

  • Removed unintentional jacoco dependency that was introduced in 2.1.0-beta01 . ( b/137782950 )

Версия 2.1.0-бета01

17 июля 2019 г.

androidx.navigation:*:2.1.0-beta01 is released. The commits included in this version can be found here .

Новые функции

  • NavigationUI now animates the removal of the Up button when using setupWithNavController() with a Toolbar or CollapsingToolbarLayout . ( b/131403621 )

Исправления ошибок

  • Fixed a timing issue when using multiple NavHostFragments with the same container with findNavController() . ( b/136021571 )

Version 2.1.0-alpha06

2 июля 2019 г.

androidx.navigation:*:2.1.0-alpha06 is released. The commits included in this version can be found here .

Новые функции

  • The app:navGraph attribute used by NavHostFragment has now been moved to the navigation-runtime artifact. Custom navigators that can be added via XML should use this attribute to gain integration with the Navigation Editor's Host panel. ( b/133880955 )

Изменения API

  • The getViewModelStore() API on NavController has been deprecated in favor of the new getViewModelStoreOwner() method that returns a ViewModelStoreOwner . ( aosp/987010 )
  • The implementation of floating window destinations, such as <dialog> destinations, has been generalized into a marker interface, FloatingWindow , that all <dialog> destinations now implement. NavigationUI methods for interacting with the top app bar now ignore FloatingWindow destinations. ( b/133600763 )

Изменения в поведении

  • Navigation now correctly keeps its state in sync with what is seen on the screen when using a <dialog> destination. As a consequence, Navigation now automatically pops <dialog> destinations when you navigate to a non-dialog and non-activity destination, such as a <fragment> destination. ( b/134089818 )

Исправления ошибок

  • Navigation now suppresses the animation that occurs when recreating the activity when handling a deep link, fixing a visual flash. ( b/130362979 )
  • Fixed a bug where the Navigation back stack would be out of sync when popping a Fragment as the initial fragment is being added. ( b/133832218 )

Version 2.1.0-alpha05

5 июня 2019 г.

androidx.navigation:*:2.1.0-alpha05 is released. The commits included in this version can be found here .

Изменения API

  • Host related APIs on NavController have been renamed and moved to a new subclass of NavController , NavHostController . ( aosp/966091 )
  • The NavController setHostOnBackPressedDispatcherOwner() method has been replaced with NavHostController 's setOnBackPressedDispatcher() method and now requires that you call setLifecycleOwner() prior to calling it. ( aosp/965409 )
  • NavHostController now contains a enableOnBackPressed(boolean) method that replaces the NavHostOnBackPressedManager class that was previously returned by setHostOnBackPressedDispatcherOwner() . ( aosp/966091 )

Исправления ошибок

  • Fixed an issue where the back stack was not correct after navigating by URI. ( b/132509387 )
  • Deep links automatically handled by NavController now only trigger once. ( b/132754763 )

Version 2.1.0-alpha04

May 16, 2019

androidx.navigation:*:2.1.0-alpha04 is released. The commits included in this version can be found here .

Исправления ошибок

  • NavHostFragment correctly respects app:defaultNavHost when intercepting the system Back button events, fixing a regression in Navigation 2.1.0-alpha03 . b/132077777
  • DialogFragmentNavigator now correctly handles popBackStack() and navigateUp() operations. b/132576764
  • Fixed an IllegalStateException: unknown destination during restore issue when repeatedly navigating between nested graphs. b/131733658

Version 2.1.0-alpha03

7 мая 2019 г.

androidx.navigation:*:2.1.0-alpha03 is released. The commits included in this version can be found here .

Известные проблемы

  • NavHostFragment continues to intercept the system Back button despite using app:defaultNavHost="false" b/132077777

Новые функции

  • You can now create <dialog> destinations that will show a DialogFragment when you navigate to them. NavHostFragment supports dialog destinations by default. b/80267254
  • In addition to calling navigate with a resource id or a NavDirections instance, you can now navigate via a Uri , which uses the <deepLink> you've added to a destination to navigate to the correct destination. b/110412864

Изменения в поведении

  • The default animations provided by NavigationUI have been sped up from 400ms to 220ms to match the default animation speed of activities and fragments. b/130055522

Изменения API

  • The createFragmentNavigator() method of NavHostFragment has been deprecated and its functionality moved to the new onCreateNavController() method to make it more clear that this is the correct entry point of adding custom Navigators when subclassing NavHostFragment . b/122802849
  • A hasDeepLink() method has been added to NavDestination to allow you to check if a given Uri can be handled by that destination or, in the case of a NavGraph , any destination in the navigation graph. b/117437718

Исправления ошибок

  • Default arguments are now correctly passed to OnDestinationChangedListener instances. b/130630686
  • NavHostFragment now intercepts system Back events using the OnBackPressedDispatcher , fixing an issue when doing conditional navigation in Fragment lifecycle methods upon returning to a Fragment. b/111598096
  • For Safe Args, an android:defaultValue=”@null” with an unspecified app:argType is now properly inferred as a string argument. b/129629192

Version 2.1.0-alpha02

April 3, 2019

androidx.navigation:*:2.1.0-alpha02 is released. The commits included in this version can be found here .

Новые функции

  • You can now create ViewModels that are scoped at a navigation graph level via the by navGraphViewModels() property delegate for Kotlin users or by using the getViewModelStore() API added to NavController . b/111614463

Изменения API

  • You can now add an app:targetPackage to an <activity> destination to limit the matching package name. It supports app:targetPackage="${applicationId}" for restricting the package to your own application id. b/110975456

Исправления ошибок

  • The android:name for <activity> destinations is no longer parsed into a Class at inflation time, preventing ClassNotFoundExceptions when using dynamic features. b/124538597

Версия 2.1.0-альфа01

March 19, 2019

This is the first alpha release of Navigation 2.1.0 .

Dependency changes

  • Navigation now depends on androidx.core:core:1.0.1 and androidx.fragment:fragment:1.1.0-alpha05 . This release also removes the dependency on androidx.legacy:legacy-support-core-utils:1.0.0 . b/128632612

Изменения API

  • A new Navigation.createNavigateOnClickListener(NavDirections) method has been added as an alternative to creating a click listener with a resource ID and Bundle. b/127631752
  • FragmentNavigator.instantiateFragment is now deprecated. The default implementation now uses FragmentFactory to instantiate Fragments. b/119054429

Исправления ошибок

  • Navigation no longer sends a null Bundle when there are arguments attached to a destination, fixing an issue when using android:defaultValue="@null" . b/128531879
  • Safe Args now depends on KotlinPoet 1.1.0, fixing an issue with extremely long package names. b/123654948

Версия 2.0.0

Версия 2.0.0

14 марта 2019 года

Navigation 2.0.0 is released with no changes from 2.0.0-rc02 .

Version 2.0.0-rc02

March 6, 2019

Navigation 2.0.0-rc02 provides new artifacts with the androidx.navigation group ID and changes its dependencies to the AndroidX equivalents.

The behavior of 2.0.0-rc02 is identical to behavior to Navigation 1.0.0-rc02 and no changes to your code should be required to update from 1.0.0-rc02 besides updating your dependencies to match the new dependencies .

Your project must have migrated to AndroidX to use 2.X releases of Navigation. Navigation 1.0 stable will be the last release using the Support Library dependencies; all future development beyond 1.0 will be based on AndroidX and build upon the 2.0 stable release.

Pre-AndroidX Dependencies

For the pre-AndroidX versions of Navigation, include these dependencies:

dependencies {
    def nav_version = "1.0.0"

    implementation "android.arch.navigation:navigation-fragment:$nav_version" // For Kotlin use navigation-fragment-ktx
    implementation "android.arch.navigation:navigation-ui:$nav_version" // For Kotlin use navigation-ui-ktx
}

For Safe args , add the following classpath in your top level build.gradle file

buildscript {
    repositories {
        google()
    }
    dependencies {
        classpath "android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0"
    }
}

Версия 1.0.0

Версия 1.0.0

14 марта 2019 года

Navigation 1.0.0 is released with no changes from 1.0.0-rc02 .

Version 1.0.0-rc02

February 26, 2019

This is the second release candidate for Navigation's 1.0.0 stable release. This release contains a number of bug fixes.

Исправления ошибок

  • Fixed an issue where popBackStack() would be ignored if the root graph did not have an ID b/126251695
  • navigateUp() now correctly handles navigating back to your app's task when called after handling a deep link without FLAG_ACTIVITY_NEW_TASK b/126082008
  • Fixed an issue with ActivityNavigator.applyPopAnimationsToPendingTransition not applying the correct pop exit animation b/126237567
  • Kotlin code generated by Safe Args now properly escapes Kotlin keywords such as in and fun in the package name associated with the R class. b/126020455

Version 1.0.0-rc01

February 21, 2019

This is a release candidate for Navigation's 1.0.0 stable release. This release contains one bug fix.

Исправления ошибок

  • Fixed an issue when using Fragments and singleTop navigation operations b/124294805

Version 1.0.0-beta02

February 12, 2019

This release includes a number of minor improvements and important bug fixes.

Новые возможности

  • You can now use 0 as an android:defaultValue for reference arguments. b/124248602

Изменения в поведении

  • Exact deep link matches are now prioritized over deep links with .* or argument matches. b/123969518

Исправления ошибок

  • popBackStack() and navigateUp now correctly return false when popping the last destination on the back stack, fixing a regression introduced in 1.0.0-beta01 . b/123933201
  • Navigation now correctly sets the ClassLoader during restoration of saved instance state, avoiding issues when using custom classes in Navigator saved state or in arguments sent to a NavDestination . b/123893858
  • Safe Args generated NavArgs classes no longer crash when restoring a Parcelable[] argument from saved instance state. b/123963545
  • Safe Args now properly cleans up unnecessary generated Kotlin classes. b/124120883

Version 1.0.0-beta01

February 4, 2019

This is the first beta release of Navigation; moving forward, the Navigation API is expected to stay stable until the next version unless there is a critical problem. This release contains some bug fixes and behavior changes.

Изменения в поведении

  • Navigation now ensures that argument default values are treated identically at runtime and through Safe Args. As a consequence, only arguments with an app:argType="reference" can have a default value point to another resource (for example, @color/colorPrimary ). Attempting to use a reference default value with a different app:argType will result in an exception when parsing the navigation XML. b/123551990
  • Safe Args now depends on Android Gradle Plugin 3.3.0 aosp/888413
  • Safe Args now depends on Kotlin 1.3.20 aosp/888414

Исправления ошибок

  • Safe Args can now be used in library and feature modules on all versions of the Android Gradle Plugin. b/121304903
  • Fixed a regression that would cause a single popBackStack() operation to pop all copies of a destination off the top of the back stack, rather than just a single destination at a time. b/123552990
  • Fixed an issue where the FragmentNavigator state would desynchronize with the NavController 's state, causing an IllegalStateException when attempting to restore the back stack. b/123803044
  • Fixed an issue where the NavigationUI handled back arrow would not appear when using ProGuard with obfuscation. b/123449431
  • The code generated by Safe Args now properly handles using an app:argType pointing to a static inner class in the format .OuterClass$InnerClass . b/123736741
  • The Java code generated by Safe Args now properly handles global actions and deeply nested destinations. b/123347762

Версия 1.0.0-Альфа11

January 23, 2019

This is a hotfix release of 1.0.0-alpha10 that fixes an issue with Safe Args.

Исправления ошибок

  • Fixes an issue where Safe Args would fail to import the Directions class associated with global actions. b/123307342

Версия 1.0.0-Alpha10

January 23, 2019

Известные проблемы

  • Safe Args fails to import the Directions class associated with global actions. b/123307342

This release contains breaking API changes; please see the Breaking Changes section below.

Новые возможности

  • Kotlin users can now use the by navArgs() property delegate to lazily get a reference to a Safe Args generated NavArgs class in an Activity or Fragment . b/122603367
  • Safe Args now allows you to generate Kotlin code by applying the androidx.navigation.safeargs.kotlin plugin. The Kotlin code is built specifically for Kotlin only modules, using default arguments and immutable classes over the builder pattern that is still available via the previous androidx.navigation.safeargs plugin. b/110263087

Behavior Changes

  • Matching deep links are now biased towards the deep link that has the most matching arguments. b/118393029
  • Calling setGraph() on a NavController will now reset the back stack. b/111450672
  • Unknown deep links no longer throw an IllegalStateException , but are ignored, fixing issues with nested or multiple NavHostFragment s. b/121340440

Критические изменения

  • The NavOptions.applyPopAnimationsToPendingTransition() method for applying pop animations to an Activity has been moved to ActivityNavigator . b/122413117
  • Safe Args now avoids duplicating identical classes for actions without arguments. The return type for no argument methods in generated NavDirections classes is now NavDirections . b/123233147
  • Safe Args generated Directions classes no longer have a public constructor - you should only be interacting with the generated static methods. b/123031660
  • Safe Args generated NavDirections classes no longer have a public constructor - they should only be generated via the static methods in the generated Directions classes. b/122963206
  • The returned Bundle from NavDirections ' getArguments() is now marked as @NonNull rather than @Nullable . b/123243957

Исправления ошибок

  • NavDeepLinkBuilder now correctly handles multiple simultaneous PendingIntent s to the same destination by using the arguments you pass in to determine the uniqueness. b/120042732
  • NavController now correctly handles popBackStack() operations when using a nested NavHostFragment or other child Fragments with a back stack. b/122770335
  • NavigationUI now correctly sets the content description of the Up button. b/120395362
  • Safe Args generated Directions classes now correctly handle global actions that have the same id as an action on a destination. b/122962504
  • Safe Args generated NavDirections classes now correctly have equal hashCode() values when equals() would return true. b/123043662
  • FragmentNavigator now throws a better error message if you attempt to do custom FragmentTransactions on the NavHostFragment 's FragmentManager . You should always use getChildFragmentManager() . b/112927148

Версия 1.0.0-Alpha09

December 18, 2018

This release contains breaking API changes; please see the Breaking Changes section below.

We have chosen not to continue development of the android.arch.navigation:navigation-testing artifact. While it has proven helpful for internal testing of NavController , we strongly recommend alternate testing strategies, such as mocking the NavController instance in order to verify that the correct navigate() calls are being done. This approach is discussed in detail in the Single Activity talk at AndroidDevSummit 2018 and we'll be working on additional documentation specifically around testing with Navigation.

Новые возможности

  • MenuItem s with menuCategory="secondary" will no longer pop the back stack when used with NavigationUI methods. b/120104424
  • AppBarConfiguration now allows you to set a fallback OnNavigateUpListener instance which will be called when navController.navigateUp() returns false . b/79993862 b/120690961

Критические изменения

  • When using an <argument> with an argType="reference" , Navigation no longer parses the reference, instead providing the raw resource ID itself. b/111736515
  • onNavDestinationSelected() now pops back to the start destination of your navigation graph by default, making them consistent with the setup methods. Add menuCategory="secondary" to your MenuItem to avoid popping the back stack. aosp/852869
  • The fromBundle() methods of generated Args classes now take a non-null Bundle instead of a nullable Bundle aosp/845616

Исправления ошибок

  • Arguments are now properly parsed from deep links as the correct argType instead of always as strings b/110273284
  • Navigation now correctly exports its public resources b/121059552
  • Safe Args is now compatible with Android Gradle Plugin 3.4 Canary 4 and higher b/119662045

Версия 1.0.0-альфа08

December 6, 2018

This release contains breaking API changes; please see the Breaking Changes section below.

Новые возможности

  • Destination labels, when used with NavigationUI methods, will now automatically replace {argName} instances in your android:label with the correct argument b/80267266
  • Navigation now depends on Support Library 28.0.0 b/120293333

Критические изменения

  • OnNavigatedListener has been renamed to OnDestinationChangedListener b/118670572
  • OnDestinationChangedListener now also passes the Bundle of arguments aosp/837142
  • The app:clearTask and app:launchDocument attributes and their associated methods have been removed. Use app:popUpTo with the root of your graph to remove all destinations from your back stack. b/119628354
  • ActivityNavigator.Extras now uses a Builder pattern and adds the ability to set any Intent.FLAG_ACTIVITY_ flags aosp/828140
  • NavController.onHandleDeepLink has been renamed to handleDeepLink aosp/836063
  • Many classes and methods not meant for subclassing, such as NavOptions , NavInflater , NavDeepLinkBuilder , and AppBarConfiguration , have been made final aosp/835681
  • The deprecated NavHostFragment.setGraph() method has been removed aosp/835684
  • The deprecated NavigationUI.navigateUp(DrawerLayout, NavController) method has been removed. aosp/835684
  • Fragment creation has been moved to FragmentNavigator , making it easier to delegate Fragment creation to a FragmentFactory . b/119054429
  • The constructor for NavGraphNavigator no longer takes a Context aosp/835340
  • NavigatorProvider is now a class, rather than an interface. The NavigatorProvider returned by getNavigatorProvider() has not changed its functionality. aosp/830660
  • NavDestination.navigate() has been removed. Call navigate() on the Navigator instead. aosp/830663
  • Significant refactoring of Navigator , removing the need for OnNavigatorNavigatedListener and instead having navigate return the NavDestination that was navigated to.
  • Navigator instances can no longer send pop events to the NavController . Consider using a OnBackPressedCallback to intercept back button presses and call navController.popBackStack() . aosp/833716

Исправления ошибок

  • popUpTo now works consistently when the destination is a <navigation> element b/116831650
  • Fixed a number of bugs that resulted in an IllegalArgumentException when using nested graphs b/118713731 b/113611083 b/113346925 b/113305559
  • The dataPattern attribute of <activity> destinations will now populate arguments from non-String arguments by calling toString() b/120161365

Safe Args

  • Safe Args supports Serializable objects, including Enum values. Enum types can set a default value by using the enum literal without the class name (eg app:defaultValue="READ" ) b/111316353
  • Safe Args supports arrays of all supported types b/111487504
  • Safe Args now ignores subfolders of resource directories b/117893516
  • Safe Args adds @Override annotations where appropriate b/117145301

Версия 1.0.0-альфа07

October 29, 2018

Новые возможности

Критические изменения

  • The navigation-testing-ktx module has been folded into the navigation-testing artifact and will no longer be published.
  • The navigation-testing artifact now has a dependency on the Kotlin standard library. The API has been changed to be more consistent with Kotlin conventions, but you can continue to use it for tests written in Java.
  • Metadata manifest registered navigation graphs are no longer supported. b/118355937
  • Actions can no longer be attached to <activity> destinations. aosp/785539

Исправления ошибок

  • Deep links now correctly parse query parameters. b/110057514
  • Activity destinations now correctly apply all enter and exit animations. b/117145284
  • Fixed crash that occurs after configuration changes when using custom Navigators. b/110763345

Safe Args

  • Safe args now have a fixed dependency on Android Gradle Plugin 3.2.1. b/113167627
  • Directions can now be generated for inner classes. b/117407555
  • Fixed an issue with generating Directions to an <include> graph. b/116542123

Версия 1.0.0-альфа06

September 20, 2018

Новые возможности

Изменения API

  • Breaking Change: The Navigator navigate() method now takes a Navigator.Extras parameter.
  • NavController's getGraph() method is now NonNull b/112243286

Исправления ошибок

  • NavigationUI.setupWithNavController() no longer leaks views if used with views from individual destinations b/111961977
  • Navigator onSaveState() is now only called once b/112627079

Safe Args

  • Navigation destination Directions classes now extend their parent's Directions class if it exists b/79871405
  • Directions and Args classes now have a useful toString() implementation b/111843389

Версия 1.0.0-альфа05

August 10, 2018

Исправления ошибок

  • Fix a bug which cause incorrect backstack behavior. b/111907708
  • Fix a bug in equals() of Generated Args classes. b/111450897
  • Fix a build failure in Safe Args. b/109409713
  • Fix a conversion from resource identifiers to java names b/111602491
  • Fix error messages about nullability in Safe Args plugin.
  • Add missing nullability annotations.

Версия 1.0.0-альфа04

July 19, 2018

Navigation 1.0.0-alpha04 and the associated Safe Args gradle plugin contains a number of API changes, behavior changes, and bug fixes.

API / Behavior Changes

  • NavHostFragment will always set the current Fragment as the primary navigation fragment, ensuring that child fragment managers are popped before the outer NavController is popped b/111345778

Safe Args

  • Breaking Change: app:type has been changed to app:argType to avoid conflicts with other libraries such as ConstraintLayout 2.0.0-alpha1 b/111110548
  • Error messages from Safe Args are now clickable b/111534438
  • Args classes now confirms that NonNull attributes are actually not null b/111451769
  • Additional NonNull annotations have been added to NavDirections and Args generated classes b/111455455 b/111455456

Исправления ошибок

  • Fixed an issue with the system back button after deep linking to a fragment destination b/111515685

Версия 1.0.0-альфа03

July 12, 2018

Navigation 1.0.0-alpha03 and the associated Safe Args gradle plugin contains a number of API changes, behavior changes, and bug fixes.

API / Behavior Changes

  • A NavigationUI.setupWithNavController method for Toolbar has been added b/109868820
  • A NavigationUI.setupWithNavController method for CollapsingToolbarLayout has been added b/110887183
  • popBackStack() now returns false when the back stack is empty or when the given destination ID is not in the back stack b/110893637
  • FragmentNavigator now ignores navigation operations after FragmentManager has saved state, avoiding “Can not perform this action after onSaveInstanceState” exceptions b/110987825

Safe Args

  • Breaking Change: Non-alphanumeric characters in action and argument names will be replaced by camel casing in the respective NavDirections method names
    • Eg DemoController.index will become setDemoControllerIndex b/79995048
    • Eg action_show_settings will become actionShowSettings b/79642240
  • Breaking Change: Arguments are now considered non-null by default. To allow null values on string and parcelable arguments, add app:nullable="true" b/79642307
  • You can now use app:type="long" with defaultValues in the form of “123L” b/79563966
  • Parcelable arguments are now supported, using a fully qualified class name for app:type . The only default value supported is "@null" b/79563966
  • Args classes now implement equals() and hashCode() b/79642246
  • The Safe Args plugin can now be applied to library projects b/80036553
  • The Safe Args plugin can now be applied to feature projects b/110011752

Исправления ошибок

  • Fixed issues when navigating during Fragment lifecycle methods b/109916080
  • Fixed issues when navigating through nested graphs multiple times b/110178671
  • Fixed issues when using setPopUpTo with the first destination in the graph b/109909461
  • Fixed issue where all app:defaultValue values were being passed as Strings b/110710788
  • aapt2 bundled with Android Gradle Plugin 3.2 Beta 01 now adds keep rules for every android:name attribute in Navigation XML files b/79874119
  • Fixed memory leak when replacing the default FragmentNavigator b/110900142

Версия 1.0.0-альфа02

June 7, 2018

Behavior Changes

  • FragmentNavigator now uses setReorderingAllowed(true) . b/109826220

  • Navigation now URLDecodes arguments parsed from deep links URLs. b/79982454

Исправления ошибок

  • Fixed an IllegalStateException when calling navigate from Fragment lifecycle methods. b/79632233

  • Navigation now depends on Support Library 27.1.1 to fix flickering when using animations. b/80160903

  • Fixed an IllegalArgumentException when using defaultNavHost="true" as a child fragment. b/79656847

  • Fixed a StackOverflowError when using NavDeepLinkBuilder. b/109653065

  • Fixed an IllegalArgumentException when navigating back to a nested graph. b/80453447

  • Fixed an issue with overlapping Fragments when using launchSingleTop . b/79407969

  • Navigation now builds the correct synthetic back stack for nested graphs. b/79734195

  • NavigationUI will now highlight the correct item when using a nested graph as a MenuItem . b/109675998

Изменения API

  • The clearTask attribute for actions and the associated API in NavOptions has been deprecated. b/80338878

  • The launchDocument attribute for actions and the associated API in NavOptions has been deprecated. b/109806636

Версия 1.0.0-альфа01

May 8, 2018

Navigation provides a framework for building in-app navigation. This initial release is 1.0.0-alpha01 .