Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

https://github.com/terrakok/Cicerone

🚦 Cicerone is a lightweight library that makes the navigation in an Android app easy.
https://github.com/terrakok/Cicerone

android bottom-navigation cicerone fragments jetpack-navigation multistack navigation

Last synced: 17 days ago
JSON representation

🚦 Cicerone is a lightweight library that makes the navigation in an Android app easy.

Lists

README

        

# Cicerone
[![Maven Central](https://img.shields.io/maven-central/v/com.github.terrakok/cicerone)](https://repo1.maven.org/maven2/com/github/terrakok/cicerone/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Cicerone-green.svg?style=true)](https://android-arsenal.com/details/1/4700)
[![Android Weekly](https://img.shields.io/badge/Android%20Weekly-250-green.svg)](http://androidweekly.net/issues/issue-250)
[![Android Weekly](https://img.shields.io/badge/Android%20Weekly-271-green.svg)](http://androidweekly.net/issues/issue-271)














Power navigation


Multibackstack


Result listeners

Cicerone (a guide who gives information about antiquities and places of interest to sightseers) is a lightweight library that makes the navigation in an Android app easy.
It was designed to be used with the MVP/MVVM/MVI patterns but will work great with any architecture.

## Main advantages
+ Is not tied to Fragments
+ Not a framework (very lightweight)
+ Short navigation calls (no builders)
+ Static typed checks for screen parameters!
+ Lifecycle-safe!
+ Functionality is simple to extend
+ Suitable for Unit Testing

## Additional features
+ Opening several screens inside single call (for example: deeplink)
+ Provides `FragmentFactory` if it needed
+ `add` or `replace` strategy for opening next screen (see `router.navigateTo` last parameter)
+ Implementation of parallel navigation (Instagram like)
+ Predefined navigator ready for Single-Activity apps
+ Predefined navigator ready for setup transition animation

## How to add Cicerone to your application
Add the dependency in your build.gradle:
```kotlin
dependencies {
//Cicerone
implementation("com.github.terrakok:cicerone:X.X.X")
}
```

Initialize the library (for example in your Application class):
```kotlin
class App : Application() {
private val cicerone = Cicerone.create()
val router get() = cicerone.router
val navigatorHolder get() = cicerone.getNavigatorHolder()

override fun onCreate() {
super.onCreate()
INSTANCE = this
}

companion object {
internal lateinit var INSTANCE: App
private set
}
}
```

## How does it work?
CiceroneDiagram.png

The `Presenter` calls the navigation method of `Router`.

```kotlin
class SamplePresenter(
private val router: Router
) : Presenter() {

fun onOpenNewScreen() {
router.navigateTo(SomeScreen())
}

fun onBackPressed() {
router.exit()
}
}
```

`Router` converts the navigation call to the set of commands and sends them to `CommandBuffer`.

`CommandBuffer` checks whether there are the `_"active"_ Navigator`:
- If yes, it passes the commands to the Navigator. `Navigator` will process them to achive the desired transition.
- If no, then `CommandBuffer` saves the commands in a queue, and will apply them as soon as a new `_"active"_ Navigator` will appear.

```kotlin
fun executeCommands(commands: Array) {
navigator?.applyCommands(commands) ?: pendingCommands.add(commands)
}
```

`Navigator` processes the navigation commands. Usually it is an anonymous class inside `Activity`.
`Activity` provides `Navigator` to the `CommandBuffer` in `_onResume_` and removes it in `_onPause_`.

**Attention**: Use `_onResumeFragments()_` with `FragmentActivity` ([more info](https://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#onResume()))

```kotlin
private val navigator = AppNavigator(this, R.id.container)

override fun onResumeFragments() {
super.onResumeFragments()
navigatorHolder.setNavigator(navigator)
}

override fun onPause() {
navigatorHolder.removeNavigator()
super.onPause()
}
```

## Navigation commands
These commands will fulfill the needs of the most applications. But if you need something special - just add it!
+ Forward - Opens new screen
![](https://github.com/terrakok/Cicerone/raw/master/media/forward_img.png)
+ Back - Rolls back the last transition
![](https://github.com/terrakok/Cicerone/raw/master/media/back_img.png)
+ BackTo - Rolls back to the needed screen in the screens chain
![](https://github.com/terrakok/Cicerone/raw/master/media/backTo_img.png)
+ Replace - Replaces the current screen
![](https://github.com/terrakok/Cicerone/raw/master/media/replace_img.png)

## Predefined navigator
The library provides predefined navigator for _Fragments_ and _Activity_.
To use, just provide it with the container and _FragmentManager_.
```kotlin
private val navigator = AppNavigator(this, R.id.container)
```

A custom navigator can be useful sometimes:
```kotlin
private val navigator = object : AppNavigator(this, R.id.container) {
override fun setupFragmentTransaction(
screen: FragmentScreen,
fragmentTransaction: FragmentTransaction,
currentFragment: Fragment?,
nextFragment: Fragment
) {
//setup your animation
}

override fun applyCommands(commands: Array) {
hideKeyboard()
super.applyCommands(commands)
}
}
```

## Screens
Describe your screens as you like e.g. create a Kotlin `object` with all application screens:
```kotlin
object Screens {
fun Main() = FragmentScreen { MainFragment() }
fun AddressSearch() = FragmentScreen { AddressSearchFragment() }
fun Profile(userId: Long) = FragmentScreen("Profile_$userId") { ProfileFragment(userId) }
fun Browser(url: String) = ActivityScreen { Intent(Intent.ACTION_VIEW, Uri.parse(url)) }
}
```

Additional you can use `FragmentFactory` for creating your screens:
```kotlin
fun SomeScreen() = FragmentScreen { factory: FragmentFactory -> ... }
```

## Screen parameters and result listener
```kotlin
//you have to specify screen parameters via new FragmentScreen creation
fun SelectPhoto(resultKey: String) = FragmentScreen {
SelectPhotoFragment.getNewInstance(resultKey)
}
```

```kotlin
//listen result
fun onSelectPhotoClicked() {
router.setResultListener(RESULT_KEY) { data ->
view.showPhoto(data as Bitmap)
}
router.navigateTo(SelectPhoto(RESULT_KEY))
}

//send result
fun onPhotoClick(photo: Bitmap) {
router.sendResult(resultKey, photoRes)
router.exit()
}
```

## Sample
To see how to add, initialize and use the library and predefined navigators see the **sample project**
(thank you [@Javernaut](https://github.com/Javernaut) for support new library version and migrate sample project to Kotlin!)

For more complex use case check out the [GitFox (Android GitLab client)](https://gitlab.com/terrakok/gitlab-client)

## Applications that use Cicerone
Яндекс.Еда — доставка еды/продуктов. Food delivery

Kaspersky Internet Security

Delivery Club – Доставка еды и продуктов

Поиск работы на hh. Вакансии рядом с домом

Whisk: Recipe Saver, Meal Planner & Grocery List

Мой Beeline (Казахстан)

Mercuryo Bitcoin Cryptowallet

ЧекСкан - кэшбэк за чеки, цены и акции в магазинах

RSS Reader для Вести.Ru

EPAM Connect

Consumer Reports: Product Reviews & Ratings

Zakaz.ru

## Participants
+ Idea and code - Konstantin Tskhovrebov (@terrakok)
+ Architecture advice, documentation and publication - Vasili Chyrvon (@Jeevuz)

## License
```
MIT License

Copyright (c) 2017 Konstantin Tskhovrebov (@terrakok)
and Vasili Chyrvon (@Jeevuz)

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.
```