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

Overview

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.
Comments
  • Flow navigation logic and a single-activity app sample

    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.

    opened by Terenfear 16
  • Handle result if activity is destroyed

    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

    opened by AlexisQapa 10
  • Passing ScreenResult from one fragment to another fragment

    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?

    opened by mjurkus 9
  • Help Needed

    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

    opened by mathemandy 8
  • "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.

    opened by emanzanoaxa 8
  • screenResolver.getScreen() returns null

    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 👍

    opened by Aissa-H 4
  • Translucent activity not finished with result

    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 ?

    opened by iandreyshev 4
  • Fragment BackStack Handling

    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.

    opened by RodrigoMRodovalho 4
  • Fragments and ViewPager

    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?

    opened by emanzanoaxa 3
  • Added the hability to have more than one listener of every type on navigation context.

    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.
    opened by emanzanoaxa 3
  • Can an Instagram Like navigation be done with this Library

    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

    opened by mathemandy 2
  • It makes sense to have a method returning the current screen (and maybe the activity/fragment) on AndroidNavigator?

    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.

    opened by emanzanoaxa 1
  • Integration with AAC Navigator

    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 ?
    opened by AlexisQapa 1
Releases(4.1.0)
  • 4.1.0(Dec 6, 2019)

  • 4.0.0(Nov 7, 2019)

    Improvements:

    • Flow navigation

    Breaking changes:

    • NavigationContext.Builder constructor receives NavigationFactory
    • NavigationContext.Builder changed methods for fragment navigation configuring
    • TransitionListener and TransitionAnimationProvider receives DestinationType instead of boolean isActivity
    Source code(tar.gz)
    Source code(zip)
  • 3.0.0(Mar 2, 2019)

    Improvements:

    • AndroidX support
    • Incremental annotation processing
    • Nullability annotations for better Kotlin support
    • Improved converters api
    • Fixing a problem with transparent activities

    Api changes:

    • ScreenSwitcher interface changed
    • Converters are interfaces now
    • getScreenOrNull method in ScreenResolver, getScreen never returns null now
    • NavigationContextBinder receives an activity in unbind method
    Source code(tar.gz)
    Source code(zip)
  • 2.2.0(Apr 10, 2018)

    • Feature: goBackToWithResult method of Navigator
    • Api change: onActivityResult and onNewIntent methods of ActivityResultHandler instead of handle
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(Feb 1, 2018)

    • canExecuteCommandImmediately and hasPendingCommands methods of Navigator
    • isBound method of NavigationContextBinder
    • Subclasses for NavigationException
    • FragmentScreenSwitcher gets NavigationFactory through constructor
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0(Jan 14, 2018)

Owner
Artur Artikov
Artur Artikov
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

null 2 Dec 22, 2022
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.

Zain Ul Hassan 4 Nov 30, 2022
[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

Gabor Varadi 1.3k Jan 2, 2023
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

Pritam Dasgupta 75 Nov 23, 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

xmartlabs 23 Apr 7, 2022
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

Jeziel Lago 21 Dec 10, 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

Breens Mbaka 6 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 This is simple

Shruti Patel 1 Jul 11, 2022
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

Arvind Meshram 5 Nov 24, 2022
Navigation Drawer Bottom Navigation View

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

Kaique Ocanha 6 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

Jeremy Feinstein 11.1k Dec 27, 2022
🎉 [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

Gaurav Kumar 1.7k Dec 31, 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

Vitali Olshevski 290 Dec 29, 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.

Adriel Café 831 Dec 26, 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.

Xinto 5 Dec 27, 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).

Kaustubh Patange 88 Dec 11, 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

Isaac Udy 216 Dec 16, 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.

Dmitry Rubtsov 205 Dec 24, 2022
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

Alperen Çevlik 3 Jul 27, 2022