Bundler
Android Intent & Bundle extensions that insert and retrieve values elegantly.
Including in your project
Gradle
Add below codes to your root build.gradle
file (not your module build.gradle file).
allprojects {
repositories {
jcenter()
}
}
And add a dependency code to your module's build.gradle
file.
dependencies {
implementation "com.github.skydoves:bundler:1.0.2"
}
Usage
Intent
intentOf
is an expression for creating an Intent using Kotlin DSL style and we can put extras using the putExtra
method. Also, we can put extras using the +
keyword in front of a key/value pair.
val intent = intentOf {
putExtra("posterId", poster.id) // put a Long type 'posterId' value.
putExtra("posterName" to poster.name) // put a String type 'posterName' value.
putExtra("poster", poster) // put a Parcelable type 'poster' value.
+("id" to userInfo.id) // put a Long type 'id' value.
+("name" to userInfo.nickname) // put a String type 'name' value.
-"name" // remove a String type 'name' value.
}
StartActivity
We can start activities using the intentOf
expression like below.
intentOf<SecondActivity> {
putExtra("id" to userInfo.id)
putExtra("name" to userInfo.nickname)
putExtra("poster", poster)
startActivity(this@MainActivity)
}
We can also use other options for creating an intent.
intentOf {
setAction(Intent.ACTION_MAIN)
addCategory(Intent.CATEGORY_APP_MUSIC)
setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(this@MainActivity)
}
bundle
bundle
is an expression for initializing lazily extra values from the intent.
class SecondActivity : AppCompatActivity() {
private val id: Long by bundle("id", -1) // initializes a Long extra value lazily.
private val name: String by bundle("name", "") // initializes a String extra value lazily.
private val poster: Poster? by bundle("poster") // initializes a Parcelable extra value lazily.
// -- stubs -- //
We can initialize a Parcelable value with a defaut value.
private val poster: Poster? by bundle("poster") { Poster.create() }
Also, we can initialize type of Array and ArrayList using bundleArray
and bundleArrayList
expression.
// initialize lazily without default values.
private val posterArray by bundleArray<Poster>("posterArray")
private val posterListArray by bundleArrayList<Poster>("posterArrayList")
or
// initialize lazily with default values.
private val posterArray by bundleArray<Poster>("posterArray") { arrayOf() }
private val posterListArray by bundleArrayList<Poster>("posterArrayList") { arrayListOf() }
Fragment
The below example shows setting arguments using the intentOf
expression.
arguments = intentOf {
+("id" to userInfo.id)
+("name" to userInfo.nickname)
+("poster" to poster)
}.extras
We can initialize argument values lazily in Fragments using the bundle
expression like below.
- val id: Long = arguments?.getLong("id", -1) ?: -1
+ val id: Long by bundle("id", -1)
- val poster: Poster? = arguments?.getParcelable("poster")
+ val poster: Poster? by bundle("poster")