Alligator
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 Screen
s.
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 Screen
s 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:
goForward(screen)
- adds a new screen and goes to it.goBack()
- removes the current screen and goes back to the previous screen.goBackWithResult(screenResult)
- goes back with ScreenResult.goBackTo(screenClass)
- goes back to a given screen.goBackToWithResult(screenClass, screenResult)
- goes back to a given screen with ScreenResult.replace(screen)
- replaces the last screen with a new screen.reset(screen)
- removes all other screens and adds a new screen.finish()
- finishes a current flow or a current top-level screen.finishWithResult(screenResult)
- finishes with ScreenResult.finishTopLevel()
- finishes a current top-level screen (that is represented by activity).finishTopLevelWithResult(screenResult)
- finishes a current top-level screen with ScreenResult.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
- TransitionListener - is called when usual screen transition (not screen switching and not dialog showing) has been executed.
- DialogShowingListener - is called when a dialog fragment has been shown.
- ScreenSwitchingListener - is called when a screen has been switched with a screen switcher.
- ScreenResultListener - is called when a screen that can return a result has finished.
- NavigationErrorListener - is called when a navigation error has occurred.
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.