Add a preference fragment where we inflate our settings screen, then do something if the user clicks on an item inside that screen.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class MySettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.settings, rootKey)
val sharedPref = activity?.getPreferences(AppCompatActivity.MODE_PRIVATE) ?: return
val vNormalMap: Preference? = findPreference(getString(R.string.pNormal_map))
vNormalMap?.onPreferenceClickListener = Preference.OnPreferenceClickListener {
it.setIcon(R.drawable.icon_radio_grey)
with (sharedPref.edit()) {
putString(getString(R.string.pNormal_map), "newHighScore")
apply()
}
val defaultValue = "resources"
val highScore = sharedPref.getString(getString(R.string.pNormal_map), defaultValue)
println("The current value is $highScore")
true
}
}
}
Where:
- 4️⃣ - Create the preference screen from an XML resource
- 6️⃣ - Declare a preference file where we can save the user's choices
- 7️⃣ - Specify an item in our XML resource as a preference object
- 9️⃣ - Listen for clicks on this item
If user clicks, do the following:
- 1️⃣1️⃣ - Change the icon of the resource
- 1️⃣3️⃣ ▸ 1️⃣6️⃣ - Set the value of the "pNormalMap" key as "newHighScore"
- 1️⃣8️⃣ - Set the default value as "resources"
- 1️⃣9️⃣ - Get the current value of "pNormalMap". If no value set, use the default value
- 2️⃣0️⃣ - Print the current value to logcat