Skip to content

Instantly share code, notes, and snippets.

@LewisRhine
Created June 9, 2017 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LewisRhine/0dfe59344f8439cfb83bb9a6b3fa8556 to your computer and use it in GitHub Desktop.
Save LewisRhine/0dfe59344f8439cfb83bb9a6b3fa8556 to your computer and use it in GitHub Desktop.
A Fragment Argument Delegate exmple
class FragmentDelegateTest : Fragment() {
companion object {
fun newInstance(someId: String) : FragmentDelegateTest {
return FragmentDelegateTest().apply { this.someId = someId }
}
}
private var someId: String? by fragmentArgument()
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
someId?.let {
callSomeApiOrSomethingIdontKnow(it)
}
}
}
inline fun <reified T> fragmentArgument() = object : ReadWriteProperty<Fragment, T?> {
override fun setValue(thisRef: Fragment, property: KProperty<*>, value: T?) {
with(thisRef) {
if (arguments == null) arguments = Bundle()
when (value) {
is String -> arguments.putString(property.name, value)
is Int -> arguments.putInt(property.name, value)
// add more as needed.
}
}
}
override fun getValue(thisRef: Fragment, property: KProperty<*>): T? {
val value = thisRef.arguments?.get(property.name)
return when (value) {
is T -> value
else -> null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment