Плавный переход android studio

Содержание
  1. Метод overridePendingTransition() — анимации между активностями
  2. Анимация при старте активности
  3. Метод overridePendingTransition()
  4. res/anim/left_out.xml
  5. res/anim/right_in.xml
  6. res/anim/top_out.xml
  7. res/anim/bottom_in.xml
  8. Анимация при помощи XML
  9. activity_down_up_enter.xml
  10. activity_down_up_exit.xml
  11. activity_down_up_close_enter.xml
  12. activity_down_up_close_exit.xml
  13. res/values/styles.xml
  14. res/values/themes.xml
  15. Урок 16. Android Navigation. Анимация переходов между пунктами назначения. Transition Framework & Animation Framework
  16. Transition Framework & Animation Framework
  17. Переходы между экранами с Animation Framework
  18. Подготовим проект
  19. Добавим ресурсы анимации
  20. Применим анимацию к переходу между экранами
  21. Building Beautiful Transitions with Material Motion for Android
  22. 1. Introduction
  23. What is Material’s motion system for Android?
  24. What you’ll build
  25. What you’ll need
  26. How would you rate your level of experience building Android apps?
  27. 2. Set up your development environment
  28. Start up Android Studio
  29. Option 1: Clone the starter codelab app from GitHub
  30. Option 2: Download the starter codelab app zip file
  31. Load the starter code in Android Studio
  32. Verify project dependencies
  33. Run the starter app
  34. Optional: Slow down device animations
  35. 3. Get familiar with the sample app code
  36. navigation_graph.xml
  37. activity_main.xml
  38. MainActivity.kt
  39. 4. Add Container Transform transition from email list to email detail page
  40. email_item_layout.xml
  41. fragment_email.xml
  42. HomeFragment.kt
  43. EmailFragment.kt
  44. HomeFragment.kt
  45. HomeFragment.kt
  46. fragment_home.xml
  47. 5. Add Container Transform transition from FAB to compose email page
  48. ComposeFragment.kt
  49. MainActivity.kt
  50. 6. Add Shared Z-Axis transition from search icon to search view page
  51. MainActivity.kt
  52. SearchFragment.kt
  53. fragment_search.xml
  54. 7. Add Fade Through transition between mailbox pages
  55. MainActivity.kt
  56. HomeFragment.kt
  57. 8. Add Container Transform transition from email address chip to card view
  58. ComposeFragment.kt
  59. ComposeFragment.kt
  60. 9. All done
  61. Next steps

Метод overridePendingTransition() — анимации между активностями

Анимация при старте активности

Прежде чем обсуждать, как создавать анимацию между активностями, рассмотрим пример создания анимации для самой первой активности, которая загружается при запуске приложения.

Создадим файл анимации rotate.xml в папке res/anim/:

Добавим в активность два ImageView:

Нам нужно запустить анимацию в методе onCreate() или в onResume():

Метод overridePendingTransition()

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

У класса Activity есть метод overridePendingTransition() и он должен идти сразу после вызова метода startActivity() или finish(). Метод принимает два параметра: ресурс анимации для запускающей активности и ресурс анимации для уходящей активности.

Таким образом вам нужно создать в папке res/anim два файла анимации и передать их идентификаторы в метод.

Предположим, первый файл будет diagonaltranslate.xml:

Второй файл — alpha.xml:

В одном из старых проектов я нашёл метод startActivity() и применил этот способ:

Запускаем проект и переходим на другую активность. Новая активность будет расти из нижнего правого угла по диагонали, а текущая активность будет становиться прозрачной. Тут всё зависит от вашей фантазии, придумайте собственные сценарии анимации. Для примера я использовал достаточно большие значения duration, на самом деле не стоит увлекаться и старайтесь указывать короткие интервалы.

Ещё пример анимации, когда экран сдвигается влево, а при возвращении обратно — вверх. Привожу только файлы анимации.

res/anim/left_out.xml

res/anim/right_in.xml

res/anim/top_out.xml

res/anim/bottom_in.xml

Анимация при помощи XML

Кстати, есть способ использовать анимацию без единой строчки Java-кода, только XML.

Создайте в папке res/anim четыре файла:

activity_down_up_enter.xml

activity_down_up_exit.xml

activity_down_up_close_enter.xml

activity_down_up_close_exit.xml

Теперь пропишем стили на основе наших файлов.

res/values/styles.xml

Создадим файл для темы.

res/values/themes.xml

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

Создайте в коде переход на второй экран и запустите проект. При нажатии на кнопку, которая запускает вторую активность, вы увидите, что второй экран приложеиня появляется с анимацией движения снизу вверх с пристукиванием. При переходе обратно на первый экран, вторая активность будет уменьшаться в размерах, сворачиваясь по центру.

Рекомендую вживую посмотреть на эффекты, вам понравится.

Источник

Урок 16. Android Navigation. Анимация переходов между пунктами назначения. Transition Framework & Animation Framework

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

Transition Framework & Animation Framework

В первой части этого урока мы анимируем переходы между экранами в нашем приложении. Для анимации в андроид-приложениях традиционно использовался Animation Framework. Он позволяет анимировать view-компоненты экрана, графические ресурсы, создавать покадровые анимации. Реализовать анимацию можно как с помощью специальных xml-ресурсов, так и непосредственно в коде. На нашем сайте уже есть урок об анимации элементов визуального интерфейса.

Начиная с версии Android KitKat 4.4 разработчики представили Transition Framework, который используется только в коде и позволяет буквально одной строкой описывать анимацию переходов, улучшающих пользовательский опыт. Например, вы наверняка видели в приложениях, как при нажатии на какой-либо элемент экрана он увеличивается и выходит на передний план. Такие переходы часто применяют к тексту или картинкам. Мы реализуем такие переходы во второй части урока.

Переходы между экранами с Animation Framework

Подготовим проект

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

Добавим ресурсы анимации

В папке res создайте папку anim и добавьте в нее такие файлы:

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

Применим анимацию к переходу между экранами

Откройте файл графа навигации res/navigation/nav_graph.xml. На вкладке дизайна выделите стрелку перехода между экранами. В панели атрибутов справа откройте раздел Animations.

У перехода есть четыре свойства, которые можно анимировать:

  • enterAnim – вход в пункт назначения
  • exitAnim – выход из пункта назначения
  • popEnterAnim — вход в пункт назначения с помощью pop action
  • popExitAnim — выход из пункта назначения с помощью pop action

Pop action – это действие, при котором экраны — пункты назначения – как бы выталкиваются из стека переходов назад в процессе навигации между экранами.

Для тех, кто не знает: стек переходов назад, или back stack – это своего рода история переходов по экранам, из которой их можно открыть путем нажатия кнопки «Назад» на устройстве. На эту тему есть урок на нашем сайте, рекомендую посмотреть для лучшего понимания.

В панели атрибутов перехода в разделе Animations напротив каждого свойства нажмите кнопку «Pick a resource» и выберите созданную нами ранее анимацию для каждого свойства.

В графе навигации вы должны получить такой код в секции action первого фрагмента:

Источник

Building Beautiful Transitions with Material Motion for Android

1. Introduction

Material Design is a system for building bold and beautiful digital products. By uniting style, branding, interaction, and motion under a consistent set of principles and components, product teams can realize their greatest design potential.

Material Components (MDC) help developers implement Material Design. Created by a team of engineers and UX designers at Google, MDC features dozens of beautiful and functional UI components and is available for Android, iOS, web and Flutter.material.io/develop

What is Material’s motion system for Android?

The Material motion system for Android is a set of transition patterns within the MDC-Android library that can help users understand and navigate an app, as described in the Material Design guidelines.

The four main Material transition patterns are as follows:

  • Container Transform: transitions between UI elements that include a container; creates a visible connection between two distinct UI elements by seamlessly transforming one element into another.
  • Shared Axis: transitions between UI elements that have a spatial or navigational relationship; uses a shared transformation on the x, y, or z axis to reinforce the relationship between elements.
  • Fade Through: transitions between UI elements that do not have a strong relationship to each other; uses a sequential fade out and fade in, with a scale of the incoming element.
  • Fade: used for UI elements that enter or exit within the bounds of the screen.

The MDC-Android library offers transition classes for these patterns, built on top of both the AndroidX Transition library ( androidx.transition ) and the Android Transition Framework ( android.transition ):

AndroidX

  • Available in the com.google.android.material.transition package
  • Supports API Level 14+
  • Supports Fragments and Views, but not Activities or Windows
  • Contains backported bug fixes and consistent behavior across API Levels

Framework

  • Available in the com.google.android.material.transition.platform package
  • Supports API Level 21+
  • Supports Fragments, Views, Activities, and Windows
  • Bug fixes not backported and may have different behavior across API Levels

In this codelab you will be using the Material transitions built on top of the AndroidX library, meaning you will be mainly focused on Fragments and Views.

What you’ll build

This codelab will guide you through building some transitions into an example Android email app called Reply, using Kotlin, to demonstrate how you can use transitions from the MDC-Android library to customize the look and feel of your app.

The starter code for the Reply app will be provided, and you will incorporate the following Material transitions into the app, which can be seen in the completed codelab’s GIF below:

  • Container Transform transition from email list to email detail page
  • Container Transform transition from FAB to compose email page
  • Shared Z-Axis transition from search icon to search view page
  • Fade Through transition between mailbox pages
  • Container Transform transition from email address chip to card view
Читайте также:  Инструкция по применению андроида самсунг

In this codelab you’ll use transitions provided by the MDC-Android motion system. For further exploration into the MDC-Android theming and component systems, you can check out the Getting started guide.

What you’ll need

  • Basic knowledge of Android development and Kotlin
  • Android Studio (download it here if you don’t already have it)
  • An Android emulator or device (available through Android Studio)
  • The sample code (see next step)

How would you rate your level of experience building Android apps?

2. Set up your development environment

Start up Android Studio

When you open Android Studio, it should display a window titled «Welcome to Android Studio». However, if this is your first time launching Android Studio, go through the Android Studio Setup Wizard steps with the default values. This step can take several minutes to download and install the necessary files, so feel free to leave this running in the background while doing the next section.

Option 1: Clone the starter codelab app from GitHub

To clone this codelab from GitHub, run the following commands:

Option 2: Download the starter codelab app zip file

Download starter app

The starter app is located within the material-components-android-motion-codelab-develop directory.

Load the starter code in Android Studio

  1. Once the setup wizard finishes and the Welcome to Android Studio window is shown, click Open an existing Android Studio project.

  1. Navigate to the directory where you had installed the sample code and select the sample directory to open the project.
  2. Wait a moment for Android Studio to build and sync the project, as shown by activity indicators along the bottom of the Android Studio window.

If Android Studio prompts you to update the project’s Android Gradle Plugin version, you should ignore the prompt as the project may not have been tested with the latest Gradle versions and updating may introduce crashes or other compilation issues.

  1. At this point, Android Studio might raise some build errors because you are missing the Android SDK or build tools, such as the one shown below. Follow the instructions in Android Studio to install/update these and sync your project. If you are still running into issues, follow the guide on updating your tools with the SDK Manager.

Verify project dependencies

The project needs a dependency on the MDC-Android library. The sample code you downloaded should already have this dependency listed, but let’s take a look at the configuration to make sure.

Navigate to the app module’s build.gradle file and make sure that the dependencies block includes a dependency on MDC-Android:

Run the starter app

  1. Ensure that the build configuration to the left of the device choice is app .
  2. Press the green Run / Play button to build and run the app.

  1. In the Select Deployment Target window, if you already have an Android device listed in your available devices, skip to Step 8. Otherwise, click Create New Virtual Device.
  2. In the Select Hardware screen, select a phone device, such as Pixel 3, and then click Next.
  3. In the System Image screen, select a recent Android version, preferably the highest API level. If it is not installed, click the Download link that is shown and complete the download.
  4. Click Next.
  5. On the Android Virtual Device (AVD) screen, leave the settings as they are and click Finish.
  6. Select an Android device from the deployment target dialog.
  7. Click Ok.
  8. Android Studio builds the app, deploys it, and automatically opens it on the target device.

If you get an INSTALL_FAILED_INVALID_APK error when building, try doing a ‘Build‘ -> ‘Clean Project‘ in Android Studio.

If you were unable to add the dependency or run the app successfully, stop and troubleshoot your developer environment. See the Android Studio guide on building and running an app for more information.

Success! The starter code for Reply’s home page should be running in your emulator. You should see the Inbox containing a list of emails.

Optional: Slow down device animations

Since this codelab involves quick, yet polished transitions, it can be useful to slow down the device’s animations in order to observe some of the finer details of the transitions as you are implementing. This can either be accomplished with adb shell commands or a Quick Settings Tile. Note that these methods of slowing down device animations will affect animations on the device outside of the Reply app as well.

Method 1: ADB Shell Commands

To slow down the device’s animations by a factor of 10x, you can run the following commands from the command line:

To reset the device’s animation speed to back to normal, run the following commands:

Method 2: Quick Settings Tile

Alternatively, to set up the Quick Settings Tile, first enable Developer Settings on your device if you haven’t done so previously:

  1. Open the device «Settings» app
  2. Scroll down to the bottom and click «About emulated device»
  3. Scroll down to the bottom and rapidly click «Build number» until Developer Settings are enabled

Next, do the following, still within the device «Settings» app, to enable the Quick Settings Tile:

  1. Click the search icon or search bar at the top of the screen
  2. Type «tiles» in the search field
  3. Click the «Quick settings developer tiles» row
  4. Click the «Window animation scale» switch

Finally, throughout the codelab, pull down the system notification shade from the top of the screen and use the icon to toggle between slow and normal speed animations.

The above instructions for setting up the Quick Settings Tile may differ slightly or not be available depending on the device and API level.

3. Get familiar with the sample app code

Let’s take a look at the code. We’ve provided an app that uses the Jetpack Navigation component library to navigate between a few different Fragments, all within a single Activity, MainActivity:

  • HomeFragment: displays a list of emails
  • EmailFragment: displays a single, full email
  • ComposeFragment: allows for the composition of a new email
  • SearchFragment: displays a search view

To learn more about the related concepts used in this codelab, please check out the following guides and exercises:

First, to understand how the app’s navigation graph is set up, open up navigation_graph.xml in the app -> src -> main -> res -> navigation directory:

Take note of how all of the fragments mentioned above are present, with the default launch fragment set to the HomeFragment via app:startDestination=»@id/homeFragment» . This XML definition of the fragment destination graph, as well as the actions, informs the generated Kotlin navigation code that you will encounter when hooking up transitions.

activity_main.xml

Next, take a look at the activity_main.xml layout in the app -> src -> main -> res -> layout directory. You’ll see the NavHostFragment which is configured with the navigation graph from above:

This NavHostFragment fills the screen and handles all of the full screen fragment navigation changes in the app. The BottomAppBar and its anchored FloatingActionButton , also in activity_main.xml , are laid out on top of the current fragment displayed by the NavHostFragment , and therefore will be shown or hidden depending on the fragment destination by the provided sample app code.

Additionally, the BottomNavDrawerFragment in activity_main.xml is a bottom drawer that contains a menu for navigating between the different email mailboxes, which is conditionally shown via the BottomAppBar Reply logo button.

MainActivity.kt

Lastly, to see an example of a navigation action being used, open up MainActivity.kt in the app -> src -> main -> java -> com.materialstudies.reply.ui directory. Locate the navigateToSearch() function, which should look like this:

This shows how you can navigate to the search view page, without any custom transition. During this codelab, you will dive into Reply’s MainActivity and four main fragments to set up Material transitions that work in tandem with the various navigation actions throughout the app.

Читайте также:  Мои устройства андроид google play

Now that you’re familiar with the starter code, let’s implement our first transition.

4. Add Container Transform transition from email list to email detail page

To begin, you will add a transition when clicking on an email. For this navigation change, the container transform pattern is well suited, as it’s designed for transitions between UI elements that include a container. This pattern creates a visible connection between two UI elements.

Before adding any code, try running the Reply app and clicking on an email. It should do a simple jump-cut, which means the screen is replaced with no transition:

A container transform in the MDC-Android library is called a MaterialContainerTransform . By default, this Transition subclass operates as a shared element transition, meaning the Android Transition system is able to pick up two views in different layouts when marked with a transitionName .

Begin by adding a transitionName attribute on the MaterialCardView in email_item_layout.xml as shown in the following snippet:

email_item_layout.xml

The transition name takes in a string resource with a parameter. You need to use the id of each email to ensure each transitionName in our EmailFragment is unique.

Reply’s minimum SDK level is 24, meaning we can directly use the android:transitionName attribute introduced in API level 21. If your app supports below API level 21, use the ViewCompat#setTransitionName method when setting your view’s transition name.

Now that you have your email list item’s transition name set, let’s do the same in the email details layout. In fragment_email.xml , set the transitionName of the MaterialCardView to the following string resource:

fragment_email.xml

Setting the «start» view ( MaterialCardView in email_item_layout.xml ) and «end» view ( MaterialCardView in fragment_email.xml ) transition names will help inform the Android Transition system of the two shared element views that are involved in this transition.

In HomeFragment.kt , replace the code in onEmailClicked with the below snippet to create the mapping from your start view (email list item) and end view (email details screen):

HomeFragment.kt

The key part of the above snippet is the FragmentNavigatorExtras . The Android Transition system will get the transition name set on the first parameter ( cardView ), and create a mapping between that transition name and the transition name string passed in as the second parameter ( emailCardDetailTransitionName ). This is how the system knows which views to find and provide to the MaterialContainerTransform instance as the «start» and «end» views to transform between.

Now that you have the plumbing configured, you can create a container transform. In the EmailFragment onCreate method, set sharedElementEnterTransition to a new instance of a MaterialContainerTransform (importing the com.google.android.material.transition version as opposed to the com.google.android.material.transition.platform version) by adding the following snippet:

EmailFragment.kt

There are a few things happening here that are noteworthy:

  • For simplicity, only the sharedElementEnterTransition is being set, as opposed to the sharedElementReturnTransition . By default, the Android Transition system will automatically reverse the enter transition when navigating back, if no return transition is set.
  • drawingViewId controls where in the view hierarchy the animating container will be placed. This allows you to show the transition below or above other elements in your UI. In Reply’s case, you’re running the container transform at the same level as your fragment container to ensure it’s drawn below the Bottom App Bar and Floating Action Button.
  • scrimColor is a property on MaterialContainerTransform which controls the color of a translucent shade drawn behind the animating container. By default, this is set to 32% black. Here it’s set to transparent, meaning no scrim will be drawn. This is because in a later step you will add an exit transition to the list of emails that pairs nicely with the container transform.
  • Lastly, we set the container colors of MaterialContainerTransform to colorSurface . When MaterialContainerTransform animates between two views, there are three «containers» it draws to the canvas: 1) a background container 2) a container for the start view and 3) a container for the end view. All three of these containers can be given a fill color and are set to transparent by default. Setting these background fill colors can be useful if your start or end view doesn’t itself draw a background, causing other elements to be seen beneath it during animation. Since all of the containers in this example should be set to colorSurface , we can use the setAllContainerColors helper method to ensure we don’t run into any visual issues.

Now try re-running the app.

Things are starting to look great! When you click on an email in the email list, a container transform should expand the list item into a full screen details page. However, notice how pressing back doesn’t collapse the email back into the list. Additionally, the email list disappears immediately at the beginning of the transition, showing the grey window background. So we’re not done yet.

Typically, this first issue of the collapse not working is because when the Android Transition system is trying to run your return transition, the list of emails hasn’t been inflated and populated into the RecyclerView yet. We need a way to wait until our HomeFragment lays out our list before we start our transitions.

The Android Transition system provides methods to do just that — postponeEnterTransition and startPostponedEnterTransition . If postponeEnterTransition is called, any entering transition to be run will be held until a closing call to startPostponedEnterTransition is called. This gives us the opportunity to «schedule» our transitions until after the RecyclerView has been populated with emails and the transition is able to find the mappings you configured.

To fix the return transition, add the following two lines to the onViewCreated method in HomeFragment.kt :

HomeFragment.kt

Try re-running the app. Pressing back after opening an email will collapse the email back into the list. Nice! Let’s keep improving the animation.

The issue of the email list disappearing is because when navigating to a new Fragment using the Navigation Component, the current Fragment is immediately removed and replaced with our new, incoming Fragment. To keep the email list visible even after being replaced, you can add an exit transition to HomeFragment .

MDC-Android provides two transitions to do this for you — Hold and MaterialElevationScale . The Hold transition simply keeps its target in its current position while MaterialElevationScale runs a subtle scale animation.

Add the below snippet to the HomeFragment onEmailClicked method to have the list of emails subtly scale out when exiting and back in when reentering:

HomeFragment.kt

A Fragment is reentering when it is coming back into view after the current Fragment is popped off the back stack. For HomeFragment , this happens when pressing back from EmailFragment . Here, this will cause our list of emails to subtly scale in when we return to the list.

Next, in order to ensure that the MaterialElevationScale transition is applied to the home screen as a whole, instead of to each of the individual views in the hierarchy, mark the RecyclerView in fragment_home.xml as a transition group.

fragment_home.xml

Reply’s minimum SDK level is 24, meaning we can directly use the android:transitionGroup attribute introduced in API level 21. If your app supports below API level 21, use the ViewGroupCompat#setTransitionGroup method when setting your view’s transition group.

At this stage, you should have a fully working container transform. Clicking on an email expands the list item into a details screen while receding the list of emails. Pressing back collapses the email details screen back into a list item while scaling up in the list of emails.

5. Add Container Transform transition from FAB to compose email page

Let’s continue with container transform and add a transition from the Floating Action Button to ComposeFragment , expanding the FAB to a new email to be written by the user. First, re-run the app and click on the FAB to see that there is no transition when launching the email compose screen.

To see the above jump-cut, make sure you click on the FAB while looking at the email list, after a fresh launch of the app. If you’ve previously opened an email during your current run of the app, then you may see a partial transition effect due to a stale exit or reenter transition. This is especially likely to happen if you’ve been using Android Studio’s Hot Reload to run the app, and it won’t be an issue once all the flows in this codelab are complete.

Читайте также:  Забыл пароль от вай фай роутера что делать андроид

While we use the same transition class, the way we configure this instance will be different since our FAB lives in MainActivity and our ComposeFragment is placed inside our MainActivity navigation host container.

In ComposeFragment.kt , add the following snippet to the onViewCreated method, making sure to import the androidx.transition version of Slide .

ComposeFragment.kt

In addition to parameters used to configure our previous container transform, startView and endView are being set manually here. Instead of using transitionName attributes to let the Android Transition system know which views should be transformed, you can specify these manually when necessary.

Now, re-run the app. You should see the FAB transforming into the compose screen (see the GIF at the end of this step).

Similar to the previous step, you need to add a transition to HomeFragment to keep it from disappearing after being removed and replaced by ComposeFragment .

Copy the below snippet into the navigateToCompose method in MainActivity before the call NavController navigate .

MainActivity.kt

Note that the duration of our MaterialElevationScale is the same as the duration of MaterialContainerTransform . This ensures the HomeFragment is held for the same amount of time as it takes for the container transform to run and will disappear as soon as the container transform is finished.

That’s it for this step! You should have a transition from the FAB to compose screen that looks like the following:

In this step, we’ll add a transition from the search icon to the full screen search view. Since there is no persistent container involved in this navigation change, we can use a Shared Z-Axis transition to reinforce the spatial relationship between the two screens and indicate moving one level upward in the app’s hierarchy.

Before adding any additional code, try running the app and tapping the search icon at the bottom right corner of the screen. This should bring up the search view screen with no transition.

To begin, find the navigateToSearch method in MainActivity , and add the following code snippet before the NavController navigate method call to set up the current fragment’s exit and reenter MaterialSharedAxis Z-Axis transitions.

MainActivity.kt

Next, add the following code snippet to the onCreate method in SearchFragment , which configures its enter and return MaterialSharedAxis transitions.

SearchFragment.kt

It’s important to note here how these two fragments move together, with regards to the MaterialSharedAxis forward boolean constructor parameter. When the MainActivity current fragment is exiting, SearchFragment will be entering. This is why, in the MainActivity current fragment, the exit transition is forward and in SearchFragment the enter transition is also forward. This will ensure that both fragments are moving in the same direction when these transition pairs are running.

The opposite is true in the backwards direction. When SearchFragment is exiting, the MainActivity current fragment will be entering. For this reason, SearchFragment is configured to return in the backward direction and the MainActivity current fragment is configured to reenter in the backward direction.

Lastly, in order to ensure that the MaterialSharedAxis transition is applied to the search screen as a whole, instead of to each of the individual views in the hierarchy, mark the LinearLayout in fragment_search.xml as a transition group.

fragment_search.xml

Reply’s minimum SDK level is 24, meaning we can directly use the android:transitionGroup attribute introduced in API level 21. If your app supports below API level 21, use the ViewGroupCompat#setTransitionGroup method when setting your view’s transition group.

That’s it! Now try re-running the app and tapping on the search icon. The home and search view screens should simultaneously fade and scale along the Z-axis in depth, creating a seamless effect between the two screens.

7. Add Fade Through transition between mailbox pages

In this step, we’ll add a transition between different mailboxes. Since we don’t want to emphasize a spatial or hierarchical relationship, we’ll use a fade through to perform a simple «swap» between lists of emails.

Before adding any additional code, try running the app, tapping on the Reply logo in the Bottom App Bar, and switching mailboxes. The list of emails should change with no transition.

To begin, find the navigateToHome method in MainActivity , and add the following code snippet before the NavController navigate method call to set up the current fragment’s exit MaterialFadeThrough transition.

MainActivity.kt

Next, open HomeFragment . In onCreate , set the fragment’s enterTransition to a new instance of MaterialFadeThrough .

HomeFragment.kt

The above setup differs slightly from previous steps due to the way mailboxes work. A mailbox is simply a HomeFragment plus an argument that tells the fragment which list of emails to display. This, in addition to the fact that HomeFragment is set to singleTop=true in our navigation graph, means you always navigate forward to new mailboxes and don’t need to deal with return or reenter transitions (transitions that run when a fragment is popped). For this reason, all you need to worry about is setting the HomeFragment enter and exit transitions.

This is an example of an architectural scenario which affects the way transitions are configured. You will need to make similar considerations when adding transitions to your own apps!

Re-run the app. When you open the bottom navigation drawer and change mailboxes, the current list of emails should fade and scale out while the new list fades and scales in. Nice!

8. Add Container Transform transition from email address chip to card view

In this step, you’ll add a transition that transforms a chip into a popup card. A container transform is used here to help inform the user that the action taken in the popup will affect the chip from which the popup originated.

Before adding any code, run the Reply app, click on an email, click the «reply» FAB, and then try clicking on a recipient’s contact chip. The chip should disappear instantly and a card with email addresses for that contact should pop into view with no animations.

You’ll be working in ComposeFragment for this step. Already added in the ComposeFragment layout are recipient chips (visible by default) and a recipient card (invisible by default). A recipient chip and this card are the two views you will create a container transform between.

To begin, open ComposeFragment and find the expandChip method. This method is called when the provided chip is clicked. Add the following code snippet above the lines that swap the recipientCardView and chip visibility, which will trigger the container transform registered via beginDelayedTransition .

ComposeFragment.kt

An important part of the above transform’s configurations is the call to addTarget . By default, TransitionManager will run the supplied transition on all views which are changing. Setting a target will ensure the container transform only runs on the single, specified target view.

If you run the app now, the chip should transform into a card of email addresses for the recipient. Next, let’s configure the return transition to collapse the card back into the chip.

In the collapseChip method in ComposeFragment , add the below code snippet to collapse the card back into the chip.

ComposeFragment.kt

Re-run the app. Clicking the chip should expand the chip into a card while clicking the card will collapse the card back into the chip. Nice!

9. All done

Using less than 100 lines of Kotlin code and some basic XML markup, the MDC-Android library has helped you create beautiful transitions in an existing app that conforms to the Material Design guidelines, and also looks and behaves consistently across all Android devices.

The completed Reply Material motion system app is available by downloading the finished codelab, or by checking out the complete branch with git: git checkout complete .

To see all of the code changes from this codelab, take a look at this diff comparison for the complete branch.

Next steps

For more information on the Material motion system, be sure to check out the spec and full developer documentation, and try adding some Material transitions to your app!

Thanks for trying Material motion. We hope you enjoyed this codelab!

Источник

Оцените статью