Skip to main content

Articles, snippets and thoughts about code from Andrew Lord.

Simplified launching of Android Activities

Published on
1 minute read

Extension functions are really great for making life easier, allowing us to add functionality to types that aren't our own. One area we can use an extension is for launching Android Activities more easily.

We can build an extension that allows all Activities to be launched via a generic type argument. An optional request code can be passed to the function, which controls whether startActivity or startActivityForResult is used to launch the Activity. By providing an intent builder function, the Intent that is fired can be customised.

inline fun <reified ActivityT : Activity> Activity.startActivity(
    requestCode: Int? = null,
    intentBuilder: Intent.() -> Unit = {}
) {
    val intent = Intent(this, ActivityT::class.java)
        .apply { intentBuilder() }
    if (requestCode == null) {
        startActivity(intent)
    } else {
        startActivityForResult(intent, requestCode)
    }
}

fun startContactCreation(fromActivity: Activity, requestCode: Int) {
    fromActivity.startActivity<ConnectionCreationActivity>(requestCode) {
        putExtra("source", ConnectionCreationSource.CONNECTIONS)
    }
}

I hope the article was useful. If you have any feedback or questions please feel free to reach out to me on Twitter.

Thanks for reading and happy coding!

Like what you read? Please share the article.

Avatar of Andrew Lord

Hi, I hope you enjoyed the article. I am Andrew - a builder of apps and developer tools. Articles on the blog focus on all aspects of Android and iOS development using Kotlin and Swift.

Subscribe via RSS