Created
October 21, 2018 08:01
-
-
Save niwatly/2ad55467299646ebf68a2197973cc500 to your computer and use it in GitHub Desktop.
Fragment Utils by Kotlin
This file contains hidden or 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
| /** | |
| * persistence property that implements Parcelable on Fragment. | |
| * The set value also write to Fragment.arguments, and always read from Fragment.arguments if need. | |
| */ | |
| class ParcelableProperty<T : Any>(private val defaultValue: T? = null) : kotlin.properties.ReadWriteProperty<Fragment, T> { | |
| var value: T? = null | |
| override operator fun getValue(thisRef: android.support.v4.app.Fragment, property: kotlin.reflect.KProperty<*>): T { | |
| if (value == null) { | |
| val args = thisRef.arguments ?: throw IllegalStateException("Cannot read property ${property.name} if no arguments have been set") | |
| @Suppress("UNCHECKED_CAST") | |
| value = args.get(property.name) as? T | |
| } | |
| return (value ?: defaultValue) ?: throw IllegalStateException("Property ${property.name} could not be read") | |
| } | |
| override operator fun setValue(thisRef: android.support.v4.app.Fragment, property: kotlin.reflect.KProperty<*>, value: T) { | |
| val args = thisRef.arguments?.let { | |
| it | |
| } ?: run { | |
| Bundle().also { | |
| thisRef.arguments = it | |
| } | |
| } | |
| val key = property.name | |
| this.value = value | |
| when (value) { | |
| is String -> args.putString(key, value) | |
| is Int -> args.putInt(key, value) | |
| is Short -> args.putShort(key, value) | |
| is Long -> args.putLong(key, value) | |
| is Byte -> args.putByte(key, value) | |
| is Boolean -> args.putBoolean(key, value) | |
| is ByteArray -> args.putByteArray(key, value) | |
| is Char -> args.putChar(key, value) | |
| is CharArray -> args.putCharArray(key, value) | |
| is CharSequence -> args.putCharSequence(key, value) | |
| is Float -> args.putFloat(key, value) | |
| is Bundle -> args.putBundle(key, value) | |
| is Binder -> BundleCompat.putBinder(args, key, value) | |
| is android.os.Parcelable -> args.putParcelable(key, value) | |
| is ArrayList<*> -> args.putParcelableArrayList(key, ArrayList(value.filterIsInstance<Parcelable>())) | |
| is java.io.Serializable -> args.putSerializable(key, value) | |
| else -> throw IllegalStateException("Type ${value.javaClass.canonicalName} of property ${property.name} is not supported") | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment