Kaptain is a small, dependencyless and easy to use Android library that helps you to navigate between activities spread over several modules.
Given the following project structure:
/app
MyApplication.kt
/feature-a
FeatureAActivity.kt
/feature-b
FeatureBActivity.kt
/feature-shared
Destination.kt
app
module imports all modules belowfeature-a
andfeature-b
imports onlyfeature-shared
feature-shared
imports nothing
First, you must list all possible destinations (Activities) of your app. Create a sealed class
that implements the KaptainDestination
interface.
Optionally, you can add arguments to your destination using a data class
.
sealed class Destination : KaptainDestination {
object FeatureA : Destination()
data class FeatureB(val message: String) : Destination()
}
Next, create a new Kaptain instance and associate your destinations with the corresponding Activities.
class MyApplication : Application() {
val kaptain = Kaptain {
add<Destination.FeatureA, FeatureAActivity>()
add<Destination.FeatureB, FeatureBActivity>()
}
}
Ideally, you should inject this instance as a singleton using a DI library. Check the sample app for an example using Koin.
Now you can navigate to any Activity, from any module:
class FeatureAActivity : AppCompatActivity() {
fun goToFeatureB() {
kaptain.navigate(
activity = this,
destination = Destination.FeatureB(message = "Ahoy!"),
requestCode = 0x123 // Optional
)
}
}
After arrive at your destination, you can retrieve it's content:
class FeatureBActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feature_b)
val importantMessage = kaptain.fromIntent<Destination.FeatureB>(this)?.message
}
}
Kaptain works great with dynamic features!
You can add/remove destinations at any time:
kaptain.add<Destination.DynamicFeatureA, DynamicFeatureAActivity>()
kaptain.remove<Destination.DynamicFeatureB>()
if (kaptain.has<Destination.DynamicFeatureA>) {
kaptain.navigate(this, Destination.DynamicFeatureA)
}
- Add the JitPack repository in your root build.gradle at the end of repositories:
allprojects {
repositories {
maven { url 'https://jitpack.io' }
}
}
- Next, add the library to your module:
dependencies {
implementation "com.github.adrielcafe.kaptain:kaptain:$currentVersion"
}