Alligator is a modern Android navigation library that will help to organize your navigation code in clean and testable way.
Java
Clone or download
Latest commit 58b364d Apr 10, 2018

README.md

Alligator

Release license

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

Features

  • Screens based on activities, fragments and dialog fragments.
  • Simple yet powerful navigation methods.
  • Independence from activity lifecycle (navigation is available even when an application is in background).
  • Passing screen arguments without boilerplate code.
  • Handling screen result in object oriented style.
  • Screen switching with nested navigation.
  • 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 {
    compile 'com.github.aartikov.Alligator:alligator:2.2.0'
    annotationProcessor 'com.github.aartikov.Alligator:alligator-compiler:2.2.0'
}

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.

sAndroidNavigator = 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 set a fragment container, a fragment manager (which by default is taken from an activity), 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)
            .containerId(R.id.fragment_container)
            .build();
    mNavigationContextBinder.bind(navigationContext);
}

@Override
protected void onPause() {
    mNavigationContextBinder.unbind();
    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(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 the last screen or the group of screens executing some common task (implemented as finishing of the current activity).
  9. finishWithResult(screenResult) - finishes with ScreenResult.
  10. 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, Class<? extends Screen> screenClassFrom,
    					Class<? extends Screen> screenClassTo, boolean isActivity, @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)
            .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.

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 activity converter.

public class SampleNavigationFactory extends GeneratedNavigationFactory {
	public SampleNavigationFactory() {
		ActivityConverter<PhoneDialerScreen> phoneDialerConverter = new ActivityConverter<>(
				(context, screen) -> new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + screen.getPhoneNumber()))
		);
		registerActivity(PhoneDialerScreen.class, null, 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 a.artikov@gmail.com
Mikhail Savin savinmike.u@gmail.com

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.