Skip to content

Instantly share code, notes, and snippets.

@zerofancy
Last active March 23, 2023 10:56
Show Gist options
  • Save zerofancy/ae22ecfeb61cac15e48206c36d77d558 to your computer and use it in GitHub Desktop.
Save zerofancy/ae22ecfeb61cac15e48206c36d77d558 to your computer and use it in GitHub Desktop.
fragment便捷传参
import android.os.Bundle
import androidx.fragment.app.Fragment
import kotlin.properties.ReadWriteProperty
class FragmentBundleDataDelegate<T : Any>(private val clazz: Class<T>, private val defaultValue: T? = null) :
ReadWriteProperty<Fragment, T?> {
@Suppress("UNCHECKED_CAST")
override fun getValue(
thisRef: Fragment,
property: KProperty<*>
): T? {
val key = property.name
return thisRef.arguments
?.get(key, clazz) ?: defaultValue
}
override fun setValue(
thisRef: Fragment,
property: KProperty<*>, value: T?
) {
val args = thisRef.arguments
?: Bundle().also(thisRef::setArguments)
val key = property.name
args.put(key, value)
}
}
fun <T> Bundle.put(key: String, value: T) {
when (value) {
is Boolean -> putBoolean(key, value)
is String -> putString(key, value)
is Int -> putInt(key, value)
is Short -> putShort(key, value)
is Long -> putLong(key, value)
is Byte -> putByte(key, value)
is ByteArray -> putByteArray(key, value)
is Char -> putChar(key, value)
is CharArray -> putCharArray(key, value)
is CharSequence -> putCharSequence(key, value)
is Float -> putFloat(key, value)
else -> throw IllegalStateException("Type of property $key is not supported")
}
}
@Suppress("IMPLICIT_CAST_TO_ANY")
private fun <T> Bundle.get(key: String, clazz: Class<T>): T? {
return when (clazz) {
Boolean::class.java -> getBoolean(key)
String::class.java -> getString(key)
Int::class.java -> getInt(key)
Short::class.java -> getShort(key)
Long::class.java -> getLong(key)
Byte::class.java -> getByte(key)
ByteArray::class.java -> getByteArray(key) ?: ByteArray(0)
Char::class.java -> getChar(key)
CharArray::class.java -> getCharArray(key) ?: CharArray(0)
CharSequence::class.java -> getCharSequence(key)
Float::class.java -> getFloat(key)
else -> throw IllegalStateException("Type of property $key is not supported")
} as? T?
}
inline fun <reified T : Any> Fragment.argument() = FragmentBundleDataDelegate(T::class.java)
// usage
class SomeFragment() {
companion object {
fun newInstance(arg1: Int?) = SomeFragment().also {
it.arg1 = arg1
}
}
private val arg1: Int? by argument()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment