Created
March 24, 2017 12:26
-
-
Save Atternatt/17dc220ef0ddb63a293f553c462eac93 to your computer and use it in GitHub Desktop.
Delegating SharedPreferences into parameters
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
object Delegate { | |
fun <Param> prefParam(activity: Context, name: String, default: Param) = PrefParam(activity, name, default) | |
} | |
class PrefParam<Param>(val context: Context, val name: String, val default: Param) : ReadWriteProperty<Any, Param> { | |
val sharedPreferences: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(context) } | |
override fun getValue(thisRef: Any, property: KProperty<*>): Param { | |
return findPreference(name, default) | |
} | |
override fun setValue(thisRef: Any, property: KProperty<*>, value: Param) { | |
putPreference(name, value) | |
} | |
@Suppress("UNCHECKED_CAST") | |
private fun <U> findPreference(name: String, default: U): U = with(sharedPreferences) { | |
val res: Any = when (default) { | |
is Long -> getLong(name, default) | |
is String -> getString(name, default) | |
is Int -> getInt(name, default) | |
is Boolean -> getBoolean(name, default) | |
is Float -> getFloat(name, default) | |
else -> throw java.lang.IllegalArgumentException("This type can be saved into Preferences") | |
} | |
res as U | |
} | |
private fun <U> putPreference(name: String, value: U) = with(sharedPreferences.edit()) { | |
when (value) { | |
is Long -> putLong(name, value) | |
is String -> putString(name, value) | |
is Int -> putInt(name, value) | |
is Boolean -> putBoolean(name, value) | |
is Float -> putFloat(name, value) | |
else -> throw java.lang.IllegalArgumentException("This type can be saved into Preferences") | |
}.apply() | |
} | |
} |
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 DataCaptionActivity : Activity(){ | |
private var dataCaptionInfo = DataCaptionInfo(this) | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
dataCaptionInfo.name = "Marc" //actualitzat a shared preferences | |
} | |
override fun onDestroy() { | |
dataCaptionInfo.clean() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment