Last active
March 28, 2023 06:51
-
-
Save passsy/3e6a12150af02120f8c6c156100277cc 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 | |
/** | |
* Extensions for simpler launching of Activities | |
*/ | |
inline fun <reified T : Any> Activity.launchActivity( | |
requestCode: Int = -1, | |
options: Bundle? = null, | |
noinline init: Intent.() -> Unit = {}) { | |
val intent = newIntent<T>(this) | |
intent.init() | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { | |
startActivityForResult(intent, requestCode, options) | |
} else { | |
startActivityForResult(intent, requestCode) | |
} | |
} | |
inline fun <reified T : Any> Context.launchActivity( | |
options: Bundle? = null, | |
noinline init: Intent.() -> Unit = {}) { | |
val intent = newIntent<T>(this) | |
intent.init() | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { | |
startActivity(intent, options) | |
} else { | |
startActivity(intent) | |
} | |
} | |
inline fun <reified T : Any> newIntent(context: Context): Intent = | |
Intent(context, T::class.java) |
I use both. If you provide a requestCode
it calls startActivityForResult
otherwise startActivity
Yep, I did research, and it's funny what I found. StartActivity calls startActivityForResult internally; then, it means that we would say its the same.
public void startActivity(Intent intent, @nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}
It's important to call the correct method though. startActivity
might be overridden or - unlikely - the internal implementation might change.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why do you use startActivityForResult instead of startActivity?
IDK, but would it be good to be able to choose which one to use?
For example, one fun launchActivity and another one fun launchActivityForResult.
What do you think? Or is it right to use alwaysstartActivityForResult?