Last active
January 29, 2026 08:46
-
-
Save opoojkk/ad04f50d352855618190f35e2fef9e4f to your computer and use it in GitHub Desktop.
利用Kotlin属性委托获取Activity传递的参数
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
| import android.app.Activity | |
| import android.content.Context | |
| import android.content.Intent | |
| import android.os.Bundle | |
| import android.os.Parcelable | |
| import kotlin.properties.ReadOnlyProperty | |
| import kotlin.reflect.KProperty | |
| class ActivityOptions { | |
| var flags: Int = 0 | |
| fun flag(flag: Int) { | |
| flags = flags or flag | |
| } | |
| } | |
| class ExtrasBuilder { | |
| val bundle = Bundle() | |
| fun int(key: String, value: Int) = bundle.putInt(key, value) | |
| fun long(key: String, value: Long) = bundle.putLong(key, value) | |
| fun string(key: String, value: String) = bundle.putString(key, value) | |
| fun boolean(key: String, value: Boolean) = bundle.putBoolean(key, value) | |
| fun parcelable(key: String, value: Parcelable) = bundle.putParcelable(key, value) | |
| } | |
| inline fun <reified T : Activity> Context.startActivity( | |
| options: ActivityOptions.() -> Unit = {}, | |
| extras: ExtrasBuilder.() -> Unit | |
| ) { | |
| val opts = ActivityOptions().apply(options) | |
| val bundle = ExtrasBuilder().apply(extras).bundle | |
| startActivity( | |
| Intent(this, T::class.java).apply { | |
| addFlags(opts.flags) | |
| putExtras(bundle) | |
| } | |
| ) | |
| } | |
| inline fun <reified T : Any> Activity.optionalExtras(key: String, defaultValue: T) = | |
| OptionalIntentExtra(key, defaultValue) | |
| class OptionalIntentExtra<T : Any>( | |
| private val key: String, private val defaultValue: T | |
| ) : ReadOnlyProperty<Activity, T> { | |
| override fun getValue(thisRef: Activity, property: KProperty<*>): T { | |
| return thisRef.intent.extras?.get(key) as? T ?: defaultValue | |
| } | |
| } | |
| inline fun <reified T : Any> Activity.requiredExtra(key: String) = RequiredIntentExtra<T>(key) | |
| class RequiredIntentExtra<T : Any>( | |
| private val key: String | |
| ) : ReadOnlyProperty<Activity, T> { | |
| override fun getValue(thisRef: Activity, property: KProperty<*>): T { | |
| return thisRef.intent.extras?.get(key) as? T ?: error("Missing required intent extra: $key") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment