Alligator is a modern Android navigation library that will help to organize your navigation code in clean and testable way.

Last update: Jul 7, 2022

Alligator

Release license

Alligator is a modern Android navigation library that will help to organize your navigation code in clean and testable way.

Features

  • Any approach you want: activity per screen, activity per flow, single activity.
  • Simple yet powerful navigation methods.
  • Lifecycle-safe (navigation is available even when an application is in background).
  • Passing screen arguments without boilerplate code.
  • Handling screen result in object oriented style.
  • Bottom navigation with separate back stack history.
  • Flexible animation configuring.

Gradle Setup

Add jitpack.io repository in project level build.gradle:

repositories {
    ...
    maven { url 'https://jitpack.io' }
}

Add the dependencies in module level build.gradle:

dependencies {
    implementation 'com.github.aartikov.Alligator:alligator:4.1.0'
    annotationProcessor 'com.github.aartikov.Alligator:alligator-compiler:4.1.0'
}

Starting from version 3.0.0 Alligator requires AndroidX.

Components to know

AndroidNavigator - the main library object. It implements Navigator and NavigationContextBinder interfaces and uses a command queue internally to execute navigation commands.

Navigator - has navigation methods such as goForward, goBack, replace and so on. It does not depend on Android SDK, so code that uses it can be tested easily. Navigator operates with Screens.

Screen - a logical representation of an application screen. It is used to indicate a screen type and pass screen arguments.

NavigationContextBinder - binds and unbinds NavigationContext to AndroidNavigator.

NavigationContext - is used to configure AndroidNavigator. It contains a reference to the current activity and all the other things needed for command execution.

Command - a command executed by AndroidNavigator. The library has a bunch of implemented commands corresponding to navigation methods. You donโ€™t need to create a command manually, AndroidNavigator creates it when a navigation method is called.

NavigationFactory - associates Screens with theirs Android implementation. Alligator generates a navigation factory for you with annotation processor, but you can extend it if needed.

ScreenSwitcher - an object for switching between several screens without theirs recreation. There are ready to use implementations of ScreenSwitcher - FragmentScreenSwitcher.

TransitionAnimation, TransitionAnimationProvider - are used to configure animations.

Quick start

1. Declare screens

Screens with arguments should be Serializable or Parcelable.

// Screen without arguments
public class ScreenA implements Screen {}

// Screen with an argument
public class ScreenD implements Screen, Serializable {
  private String mMessage;

  public ScreenD(String message) {
     mMessage = message;
  }

  public String getMessage() {
     return mMessage;
  }
}

2. Register screens

Mark your activities and fragments with @RegisterScreen annotation. Alligator looks for this annotations to create GeneratedNavigationFactory.

@RegisterScreen(ScreenA.class)
public class ActivityA extends AppCompatActivity 
@RegisterScreen(ScreenD.class)
public class FragmentD extends Fragment

3. Create AndroidNavigator

It should be a single instance in your application.

androidNavigator = new AndroidNavigator(new GeneratedNavigationFactory());

4. Set NavigationContext

Use NavigationContext.Builder to create NavigationContext. In the simplest case just pass a current activity to it. You can also configure fragment navigation, a screen switcher, animation providers and listeners.

Activities are responsible to bind and unbind NavigationContext. Bind it in onResumeFragments (when state of an activity and its fragments is restored) and unbind in onPause (when an activity becomes inactive).

@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    NavigationContext navigationContext = new NavigationContext.Builder(this, androidNavigator.getNavigationFactory())
            .fragmentNavigation(getSupportFragmentManager(), R.id.fragment_container)
            .build();
    mNavigationContextBinder.bind(navigationContext);
}

@Override
protected void onPause() {
    mNavigationContextBinder.unbind(this);
    super.onPause();
}

5. Call navigation methods

mNavigator.goForward(new ScreenD("Message for D"));
// or
mNavigator.goBack();

Navigator provides these navigation methods:

  1. goForward(screen) - adds a new screen and goes to it.
  2. goBack() - removes the current screen and goes back to the previous screen.
  3. goBackWithResult(screenResult) - goes back with ScreenResult.
  4. goBackTo(screenClass) - goes back to a given screen.
  5. goBackToWithResult(screenClass, screenResult) - goes back to a given screen with ScreenResult.
  6. replace(screen) - replaces the last screen with a new screen.
  7. reset(screen) - removes all other screens and adds a new screen.
  8. finish() - finishes a current flow or a current top-level screen.
  9. finishWithResult(screenResult) - finishes with ScreenResult.
  10. finishTopLevel() - finishes a current top-level screen (that is represented by activity).
  11. finishTopLevelWithResult(screenResult) - finishes a current top-level screen with ScreenResult.
  12. switchTo(screen) - switches a screen using a ScreenSwitcher.

Navigation methods can be called at any moment, even when a NavigationContext is not bound. When a navigation method is called an appropriate Command is created and placed to a command queue. AndroidNavigator can execute commands only when a NavigationContext is bound to it, in other case a command will be postponed. You can combine navigation methods arbitrarily (for example call two goBack() one by one). This works for activities too because AndroidNavigator unbinds a NavigationContext by itself after activity finishing or starting.

See how navigation methods work in simple navigation sample an navigation methods sample.

6. Get screen arguments

To get screen arguments from an activity or a fragment use ScreenResolver.

mScreenResolver = SampleApplication.sAndroidNavigator.getScreenResolver();
ScreenD screen = mScreenResolver.getScreen(this); // 'this' is Activity or Fragment
String message = screen.getMessage();

Advanced topics

Configure animations

Create TransitionAnimationProvider and set it to NavigationContext.

public class SampleTransitionAnimationProvider implements TransitionAnimationProvider {
    @Override
    public TransitionAnimation getAnimation(TransitionType transitionType,
                                            DestinationType destinationType,
                                            Class<? extends Screen> screenClassFrom,
                                            Class<? extends Screen> screenClassTo,
                                            @Nullable AnimationData animationData) {
        switch (transitionType) {
            case FORWARD:
                return new SimpleTransitionAnimation(R.anim.slide_in_right, R.anim.slide_out_left);
            case BACK:
                return new SimpleTransitionAnimation(R.anim.slide_in_left, R.anim.slide_out_right);
            default:
                return TransitionAnimation.DEFAULT;
        }
    }
}
    NavigationContext navigationContext = new NavigationContext.Builder(this, navigationFactory)
            .transitionAnimationProvider(new SampleTransitionAnimationProvider())
            .build();

Lollipop transition animations are also supported, see shared element animation sample.

Switch screens

A navigation method switchTo is similar to replace. The difference is that during screen switching screens can be reused. For example if there are three tabs in your application and each tab screen is represented by a fragment, there are no reason to create more than three fragments. Screen switching is especially useful if you want to create a nested navigation where each tab has its own backstack.

To make screen switching posible a special object ScreenSwitcher should be created and set to NavigationContext. The library provides a ScreenSwitcher implementation called FragmentScreenSwitcher. Screens passed to FragmentScreenSwitcher are used as keys to identify fragments so they must have equals and hashCode methods correctly overridden.

See how screen switching works in simple screen switcher sample an advanced screen switcher sample.

Flows

Flow is a group of screen executing some common task. There are two ways to create flows. The first one is to use activities for flows and fragments for nested screens. There is nothing special here. The second way is to use FlowScreens. It allows to create fragment-based flows with nested child fragments. Screens marked with FlowScreen interface are considered to be flows. You can configure this type of navigation using flowFragmentNavigation and fragmentNavigation methods of NavigationContext.Builder.

For more details see flow sample.

Open dialogs

To open a dialog register screen implemented by a dialog fragment and start it with goForward method.

Listen navigation

These types of listeners can be set to NavigationContext

Start external activity

To use an external activity (for example a phone dialer) extend GeneratedNavigationFactory and register a screen with a custom intent converter.

public class PhoneDialerConverter extends OneWayIntentConverter<PhoneDialerScreen> {
    @Override
    public Intent createIntent(Context context, PhoneDialerScreen screen) {
        return new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + screen.getPhoneNumber()));
    }
}
public class SampleNavigationFactory extends GeneratedNavigationFactory {
    public SampleNavigationFactory() {
        registerActivity(PhoneDialerScreen.class, new PhoneDialerConverter());
    }
}

Start it with goForward method. Use NavigationErrorListener to check that an activity has been succesfully resolved.

Handle screen result

A screen can return ScreenResult to a previous screen. It is like startActivityForResult, but with Alligator there are no needs to declare request codes and handle onActivityResult manually. Alligator defines unique request codes for screens implemented by activities that can return results. For screens implemented by fragments Alligator uses usual listeners.

Declare and register screen result classes. Return a result with goBackWithResult or finishWithResult methods of Navigator. Use ActivityResultHandler and ScreenResultListener to handle screen result.

See how to do it in screen result sample.

Developed by

Artur Artikov [email protected]
Mikhail Savin [email protected]

License

The MIT License (MIT)

Copyright (c) 2017 Artur Artikov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

GitHub

https://github.com/aartikov/Alligator
Comments
  • 1. Flow navigation logic and a single-activity app sample

    I was experimenting with single-activity apps and decided to try to implement reusable flows logic. Basically it's similar to the existing screen switching logic, but it has more navigation commands and allows you to return results to another naviagation stacks. My implementation works only with nested fragments, but I think it's possible to implement it with activities. All new commands are very similar to the existing ones but operate only with "flow" screens to avoid clashing with regular activities and fragments that don't host another screens inside. All corresponding navigator methods have the same parameters as their regular counterparts. So, the list is (new command - regular analogue):

    1. addFlow - goForward
    2. replaceFlow - replace
    3. resetFlow - reset
    4. finishFlow - finish
    5. backToFlow - backTo
    6. back - updated an existing version, now it checks for existing flow fragments in a top-level fragment manager using FragmentFlowManager

    Finish and backTo also have "with result" variants. All new commands delegate activity/fragment creation logic to an implementation of FlowManager class, kind of like SwitchToCommand does with implementations of ScreenSwitcher class.

    The sample is very simple and just shows a basic behavior of single-activity navigation as well as some usages of navigation flows.

    Reviewed by Terenfear at 2019-07-22 17:14
  • 2. Handle result if activity is destroyed

    Hi,

    Would this lib allow a result to be passed across multiple activities like : A need result D produce result But B is destroyed by android A -> B (destroyed) -> C -> D

    Reviewed by AlexisQapa at 2018-03-21 09:41
  • 3. Passing ScreenResult from one fragment to another fragment

    In current implementation I only see possibility to register one screen result listener when building NavigationContext.

    I need to pass result from one fragment to another. It is possible using setTargetFragment(fragment, requestCode)

    Is there a way, that I can't find, to achieve such behaviour?

    Reviewed by mjurkus at 2018-01-29 14:42
  • 4. Help Needed

    Can you explain this Part of the code Fragment fragment = mScreenSwitcher.getCurrentFragment(); if (fragment != null && fragment instanceof ContainerIdProvider) { builder.containerId(((ContainerIdProvider) fragment).getContainerId()) .fragmentManager(fragment.getChildFragmentManager()); // Use child fragment manager for nested navigation }

    I am trying to play with nested screens but cannot get them to work when i press the back button

    Reviewed by mathemandy at 2018-11-01 12:36
  • 5. "Race condition" when using switchTo()

    I have activity A that is calling switchTo() to load a fragment, but the command is queued because I have a LockActivity that shows a pin lock screen when "onStart()" is called from any Activity. That makes the switchTo() command to wait in the queue because the navigation to the lock activity is being executed. Then when the navigation context is set on that lock activity the switchTo command is executed, but on that activity I don't have a ScreenSwitcher set because I don't need to load any fragment there. That throws a NavigationException.

    I propose to give access to the command queue to be able to manage that weird cases, but maybe there's a more elegant or more robust solution for that.

    EDIT: I added a flag on the command interface meaning if the command can be discarded if no screen switcher is present, by default is always false, I'll make a pull request if you want to accept it.

    Reviewed by emanzanoaxa at 2018-01-30 15:21
  • 6. screenResolver.getScreen() returns null

    Hi ๐Ÿ‘‹,

    Thank you for this great lib!

    I have a problem when I try to get a the current activity Screen in the onCreate() of it. The screenResolver returns a null for the .getScreen() call curiously.

    I have registered my Activity and it's corresponding Screen in the NavigationFactory.

    Here is my Activity and Screen declaration :

    class LoginActivity : BaseActivity() {
    ...
    data class Screen(
            val myString: String? = null
        ): me.aartikov.alligator.Screen, Serializable
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
         screenResolver.getScreen(this) //returns null
    }
    

    Note that because I haven't migrate my app to AndroidX, I am currently on the version 2.2.0. That's why the #16 issue didn't help me a lot for the moment.

    Have you any suggestion for me ?

    Thank you in advance ๐Ÿ‘

    Reviewed by Aissa-H at 2019-03-22 10:53
  • 7. Translucent activity not finished with result

    Hi, I have android:windowIsTranslucent activity which should return result, but it happens only if rotate screen after call FinishWithResult.

    Example.1

    Open ForegroundActivity from BackgroundActivity unbind BackgroundActivity bind ForegroundActivity Call FinishWithResult in ForegroundActivity unbind ForegroundActivity bind BackgroundActivity Now we stay in the BackgroundActivity

    Example.2

    Open ForegroundActivity from BackgroundActivity unbind BackgroundActivity bind ForegroundActivity Rotate 1 unbind ForegroundActivity bind ForegroundActivity bind BackgroundActivity unbind BackgroundActivity Call FinishWithResult, bat nothing happens. We stay at ForegroundActivity, but need BackgroundActivity Rotate 2 unbind ForegroundActivity bind ForegroundActivity bind BackgroundActivity unbind BackgroundActivity unbind ForegroundActivity bind BackgroundActivity Now we stay in the BackgroundActivity

    I think lifecycle for BackgroundActivity if we use android:windowIsTranslucent is not typical: https://tech.pic-collage.com/something-about-android-windowistranslucent-641cc02ff66f

    I have the same problem when test sample app from this repository. Is library knows about it ?

    Reviewed by iandreyshev at 2018-10-03 07:31
  • 8. Fragment BackStack Handling

    Hello, Im trying to understand how can I achieve the fragment backstack handling. Im running the sample advancedscreenswitchersample but when I go though fragments and touch on back button it closes the app.

    Im running on Nexus 5x - Android 8.1.0

    Thanks.

    Reviewed by RodrigoMRodovalho at 2018-06-19 02:36
  • 9. Fragments and ViewPager

    Is there a way to use switchTo() or other command on a fragment view pager? Or a way to imitate the ViewPager behavior using animations without losing the swipe functionality?

    Reviewed by emanzanoaxa at 2018-01-24 11:58
  • 10. Added the hability to have more than one listener of every type on navigation context.

    • Now you can have multiple Transition, DialogShowing...listeners on the navigation context.
    • Removed default listener implementations, not needed anymore.
    • Fixed sample projects with new changes.
    Reviewed by emanzanoaxa at 2017-09-05 07:55
  • 11. Can an Instagram Like navigation be done with this Library

    I tested the advanceSwitcher sample and noticed that when the stacks for a tab are emptied, it closes the app, while other stacks are still on other stab.

    Question 1. Can i make just one entry point to the app - (this way all stacks can end inn this tab) Question 2. Can all stacks be emptied before closing the App

    Reviewed by mathemandy at 2018-10-31 10:03
  • 12. It makes sense to have a method returning the current screen (and maybe the activity/fragment) on AndroidNavigator?

    It can be useful for example for knowing which screen is being displayed when receiving a notification, to know if you must resume that activity in case is already on the stack or if you need to recreate that screen.

    And another question, there are plans to implement some sort of navigation stack using screens? Like the one you can create on a notification using intents, to preserve the navigation stack when navigating to a hierarchically deep screen.

    Reviewed by emanzanoaxa at 2018-10-04 09:28
  • 13. Integration with AAC Navigator

    Hi, as part of the new JetPack along with android architecture components Google released a navigation component (https://developer.android.com/topic/libraries/architecture/navigation/). While the java part seems quite close to what Alligator does, there is a XML/UI integration with features like deep links. (I don't care much about the XML thing but the way it's allow you to build flows with deep links is convenient)

    So I'm wondering :

    • is there is something to do to make this new component works great with alligator ?
    • will you maintain alligator while google will push people to its navigator ?
    Reviewed by AlexisQapa at 2018-05-29 09:33
AndroidBriefActions - Android library for sending and observing non persistent actions such as showing a message; nice readable way to call navigation actions from ViewModel or Activity/Fragment.

implementation "com.vladmarkovic.briefactions:briefactions:$briefActionsVersion" Benefits Why use brief-actions library pattern: Prevent short-term ac

Jul 25, 2021
Animated Tab Bar is an awesome navigation extension that you can use to add cool, animated and fully customizable tab navigation in your apps
Animated Tab Bar is an awesome navigation extension that you can use to add cool, animated and fully customizable tab navigation in your apps

Animated Tab Bar is an awesome navigation extension that you can use to add cool, animated and fully customizable tab navigation in your apps. The extension provides handy methods and properties to change the behaviour as well as the appearance of the navigation bar.

Jul 27, 2022
[ACTIVE] Simple Stack, a backstack library / navigation framework for simpler navigation and state management (for fragments, views, or whatevers).
[ACTIVE] Simple Stack, a backstack library / navigation framework for simpler navigation and state management (for fragments, views, or whatevers).

Simple Stack Why do I want this? To make navigation to another screen as simple as backstack.goTo(SomeScreen()), and going back as simple as backstack

Aug 12, 2022
This library will help to show the polyline in dual color similar as Uber.
This library will help to show the polyline in dual color similar as Uber.

Dual-color-Polyline-Animation This library will help to show the polyline in dual color similar as Uber with animation in the demo. Demo Steps: Pass t

Jun 26, 2022
A lightweight library to help you navigate in compose with well typed functions.

TypedNavigation A lightweight library to help you navigate in compose with well typed functions. Installation: You can add this library to your projec

Apr 7, 2022
Android multi-module navigation built on top of Jetpack Navigation Compose
Android multi-module navigation built on top of Jetpack Navigation Compose

MultiNavCompose Android library for multi-module navigation built on top of Jetpack Navigation Compose. The goal of this library is to simplify the se

Apr 16, 2022
DSC Moi University session on using Navigation components to simplify creating navigation flow in our apps to use best practices recommended by the Google Android Team

Navigation Components Navigate between destination using safe args How to use the navigation graph and editor How send data between destinations Demo

Feb 3, 2022
Bottom-App-Bar-with-Bottom-Navigation-in-Jetpack-compose-Android - Bottom App Bar with Bottom Navigation in Jetpack compose
Bottom-App-Bar-with-Bottom-Navigation-in-Jetpack-compose-Android - Bottom App Bar with Bottom Navigation in Jetpack compose

Bottom-App-Bar-with-Bottom-Navigation-in-Jetpack-compose-Android This is simple

Jul 11, 2022
New style for app design simple bottom navigation with side navigation drawer UI made in Jetpack Compose.๐Ÿ˜‰๐Ÿ˜Ž
New style for app design simple bottom navigation with side navigation drawer UI made in Jetpack Compose.๐Ÿ˜‰๐Ÿ˜Ž

BottomNavWithSideDrawer New style for app design simple bottom navigtaion with side navigation drawer UI made in Jetpack Compose. ?? ?? (Navigation Co

Jul 6, 2022
Navigation Drawer Bottom Navigation View
Navigation Drawer Bottom Navigation View

LIVE #019 - Toolbar, Navigation Drawer e BottomNavigationView com Navigation Com

Jun 15, 2022
An Android library that allows you to easily create applications with slide-in menus. You may use it in your Android apps provided that you cite this project and include the license in your app. Thanks!

SlidingMenu (Play Store Demo) SlidingMenu is an Open Source Android library that allows developers to easily create applications with sliding menus li

Aug 17, 2022
๐ŸŽ‰ [Android Library] A light-weight library to easily make beautiful Navigation Bar with ton of ๐ŸŽจ customization option.
๐ŸŽ‰ [Android Library] A light-weight library to easily make beautiful Navigation Bar with ton of ๐ŸŽจ customization option.

Bubble Navigation ?? A light-weight library to easily make beautiful Navigation Bars with a ton of ?? customization options. Demos FloatingTopBarActiv

Aug 10, 2022
A small and simple, yet fully fledged and customizable navigation library for Jetpack Compose
A small and simple, yet fully fledged and customizable navigation library for Jetpack Compose

A small and simple, yet fully fledged and customizable navigation library for Jetpack Compose

Aug 12, 2022
๐Ÿ›ธVoyager is a pragmatic navigation library built for, and seamlessly integrated with, Jetpack Compose.
๐Ÿ›ธVoyager is a pragmatic navigation library built for, and seamlessly integrated with, Jetpack Compose.

Voyager is a pragmatic navigation library built for, and seamlessly integrated with, Jetpack Compose.

Aug 9, 2022
A small navigation library for Jetpack Compose with state saving, backstack and animations support.

A small navigation library for Jetpack Compose with state saving, backstack and animations support.

Jul 24, 2022
A small navigation library for Android to ease the use of fragment transactions & handling backstack (also available for Jetpack Compose).
A small navigation library for Android to ease the use of fragment transactions & handling backstack (also available for Jetpack Compose).

A small navigation library for Android to ease the use of fragment transactions & handling backstack (also available for Jetpack Compose).

Jul 23, 2022
A simple navigation library for Android ๐Ÿ—บ๏ธ

Enro ??๏ธ A simple navigation library for Android "The novicesโ€™ eyes followed the wriggling path up from the well as it swept a great meandering arc ar

Aug 4, 2022
๐Ÿง› Fragula is a swipe-to-dismiss extension for navigation component library for Android
๐Ÿง› Fragula is a swipe-to-dismiss extension for navigation component library for Android

Fragula is a swipe-to-dismiss extension for navigation component library for Android.

Aug 12, 2022
A library that you can use for bottom navigation bar. Written with Jetpack Compose
A library that you can use for bottom navigation bar. Written with Jetpack Compose

FancyBottomNavigationBar A library that you can use for bottom navigation bar. W

Jul 27, 2022