Skip to content

Instantly share code, notes, and snippets.

@denebchorny
Forked from passsy/KIntent.kt
Last active July 20, 2020 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save denebchorny/e0733856078bcd71fedaa04165a8a916 to your computer and use it in GitHub Desktop.
Save denebchorny/e0733856078bcd71fedaa04165a8a916 to your computer and use it in GitHub Desktop.
Kotlin extension functions to start a generic Activity
package com.pascalwelsch.extensions
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
/**
* Edited by Deneb Asecas
* Extensions for simpler launching of Activities
* Original source: Source: https://gist.github.com/wajahatkarim3/d3a728dbb20002dc54ac44bad40e4077
*/
inline fun <reified T : Any> Activity.launchActivity(
requestCode: Int = -1,
options: Bundle? = null,
@AnimRes enterAnimRes: Int? = null,
@AnimRes exitAnimRes: Int? = null,
noinline init: Intent.() -> Unit = {}
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
startActivityForResult(newIntent<T>(this, init), requestCode, options)
else
startActivityForResult(newIntent<T>(this, init), requestCode)
if (enterAnimRes != null && exitAnimRes != null) {
overridePendingTransition(enterAnimRes, exitAnimRes)
}
}
inline fun <reified T : Any> Context.launchActivity(
options: Bundle? = null,
noinline init: Intent.() -> Unit = {}
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
startActivity(newIntent<T>(this, init), options)
else
startActivity(newIntent<T>(this, init))
}
inline fun <reified T : Any> Fragment.launchActivity(
requestCode: Int = -1,
options: Bundle? = null,
@AnimRes enterAnimRes: Int? = null,
@AnimRes exitAnimRes: Int? = null,
noinline init: Intent.() -> Unit = {}
) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
startActivityForResult(newIntent<T>(requireContext(), init), requestCode, options)
else
startActivityForResult(newIntent<T>(requireContext(), init), requestCode)
if (enterAnimRes != null && exitAnimRes != null) {
activity?.overridePendingTransition(enterAnimRes, exitAnimRes)
}
}
inline fun <reified T : Any> newIntent(
context: Context,
noinline init: Intent.() -> Unit = {}
): Intent {
val intent = Intent(context, T::class.java)
intent.init()
return intent
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment