-
-
Save denebchorny/e0733856078bcd71fedaa04165a8a916 to your computer and use it in GitHub Desktop.
Kotlin extension functions to start a generic Activity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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