Created
June 9, 2017 20:05
-
-
Save LewisRhine/0dfe59344f8439cfb83bb9a6b3fa8556 to your computer and use it in GitHub Desktop.
A Fragment Argument Delegate exmple
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
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