Elye
Elye

Reputation: 60211

Sharing setting names and default value in PreferenceScreen and Code

I have my PreferenceSettings xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <SwitchPreferenceCompat
            app:defaultValue="true"
            app:key="notifications"
            app:title="Enable message notifications"/>

</androidx.preference.PreferenceScreen>

To get the value in code, I write

PreferenceManager.getDefaultSharedPreferences(this).getBoolean("notifications", true)

From here, you could see that I wrote notifications twice and the default value true twice.

Is there a way to share them (e.g. in some common resources), so I could easily refactor them in without need to do in two places?

Upvotes: 0

Views: 173

Answers (1)

Elye
Elye

Reputation: 60211

Found a way to do so

I create in values folder a file name settings.xml which contains

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="my_default">true</bool>
    <string name="my_title">Enable message notifications</string>
    <string name="my_key">notifications</string>
</resources>

In my Preference Setting, I just have reference to these keys

<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <SwitchPreferenceCompat
            app:defaultValue="@bool/my_default"
            app:key="@string/my_key"
            app:title="@string/my_titleg"/>

</androidx.preference.PreferenceScreen>

And my code is

PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
    resources.getString(R.string.my_key),
    resources.getBoolean(R.bool.my_default))

With that, we could have a common place for for the key, title and default value shared by the XML and the code.

Upvotes: 2

Related Questions