Those kotlin handy extensions, creating a new Activity.

Alejandro Moya
2 min readSep 28, 2018

--

Today i’m going to leave here a little extension i created to build a new intent that starts a new activity, something we do almost all the time in android development.

When doing this we always have to call different methods several times, what if we could reduce this to some optional parameters and just start the activity with the parameters we need?

Lets do it!:

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable

fun Context.newActivity(destination: Class<*>, flags: Array<Int>? = null, extras: Array<Pair<String, Any>>? = null, options: Bundle? = null) {
val intent = Intent(this, destination)
flags?.forEach { intent.addFlags(it) }
extras?.forEach {
val extraValue = it.second
when (extraValue) {
is String -> intent.putExtra(it.first, extraValue)
is Int -> intent.putExtra(it.first, extraValue)
is Boolean -> intent.putExtra(it.first, extraValue)
is Double -> intent.putExtra(it.first, extraValue)
is Float -> intent.putExtra(it.first, extraValue)
is Long -> intent.putExtra(it.first, extraValue)
is Short -> intent.putExtra(it.first, extraValue)
is Byte -> intent.putExtra(it.first, extraValue)
is Char -> intent.putExtra(it.first, extraValue)
is IntArray -> intent.putExtra(it.first, extraValue)
is BooleanArray -> intent.putExtra(it.first, extraValue)
is DoubleArray -> intent.putExtra(it.first, extraValue)
is FloatArray -> intent.putExtra(it.first, extraValue)
is LongArray -> intent.putExtra(it.first, extraValue)
is ShortArray -> intent.putExtra(it.first, extraValue)
is ByteArray -> intent.putExtra(it.first, extraValue)
is CharArray -> intent.putExtra(it.first, extraValue)
is CharSequence -> intent.putExtra(it.first, extraValue)
is Bundle -> intent.putExtra(it.first, extraValue)
is Parcelable -> intent.putExtra(it.first, extraValue)
is Array<*> -> intent.putExtra(it.first, extraValue)
}
}
startActivity(intent, options)
}

As you can see, the method expects a Class, this will be the destination activity(as the parameter specifies), next we have the regular intent modifiers.

We can send the flags in an array, easier right?

Also with extras we can have the same treatment, checking the types to make the right call.

this extension can be used in the most basic way:

newActivity(MyNewActivity::class.java)

or we can add some more info:

val flags = arrayOf(Intent.FLAG_ACTIVITY_NO_HISTORY)
val extras = arrayOf(Pair("MyExtraString", "Extra string"), Pair("MyIntExtra", 3))
newActivity(MyNewActivity::class.java, flags = flags, extras = extras)

you can play around with it.

Hope this is useful, if you have any suggestions please leave a comment.

--

--

Alejandro Moya

Mobile developer, Father, geek, this is my first attempt at having a blog, be kind 😄