Delegates for safe dealing with fragments' arguments.
Add the dependency:
repositories {
mavenCentral()
google()
}
dependencies {
implementation("com.redmadrobot.extensions:fragment-args-ktx:1.3.6-1")
}
class FragmentWithArgs : Fragment() {
companion object {
fun newInstance(flag: Boolean, screenName: String? = null): Fragment {
return FragmentWithArgs().apply {
this.someFlag = flag
this.screenName = screenName
}
}
}
private var someFlag by arguments.boolean()
private var screenName by arguments.stringNullable()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
println("someFlag = $someFlag")
println("screenName = $screenName")
}
}
For nullable types you can use functions with suffix Nullable
:
string() -> stringNullable()
intArray() -> intArrayNullable()
parcelableList() -> parcelableListNullable()
Primitive types can't be nullable, so there are no intNullable()
, floatNullable()
, etc.
By default, the key for getting argument from bundle is the property name. You can override it with parameter if you need:
val overrideKey by arguments.boolean("isOverrideKey")
If you not assign any value to a property, will be returned default value on property reading.
You can specify default value with parameter default
:
val index by arguments.int { 1 }
// or
val index by arguments.int(default = { 1 })
If you've not implemented
default
parameter, reading a value that wasn't written before will throwIllegalStateException
.
Merge requests are welcome. For major changes, please open an issue first to discuss what you would like to change.