Question

Using Android Annotations. My prefs:

@SharedPref(value = SharedPref.Scope.APPLICATION_DEFAULT)
public interface MyPreferences {
    @DefaultBoolean(true)
    boolean myOption();
}

The preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <CheckBoxPreference
        android:key="myOption"
        android:title="My Option Name"/>
</PreferenceScreen>

My PreferencesActivity:

public class MyPreferencesActivity extends PreferenceActivity{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

The problem is: in spite of the default value of myOption is true (and indeed - it is when calling MyPreferences_.myOption().get()) the checkbox in the preferences activity is unchecked by default.

The same happens for String preferences. They return default string given in @DefaultString annotation but it is not displayed in the PreferenceActivity. Only after I change the preference value from the activity, it is properly displayed.

Was it helpful?

Solution

I resolved default values duplication by:

values/preferences_defaults.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="default_myOption">true</bool>
    <string name="default_myString">my string</string>
</resources>

Prefs:

@SharedPref(value = SharedPref.Scope.APPLICATION_DEFAULT)
public interface MyPreferences {
    @DefaultRes(R.bool.default_myOption)
    boolean myOption();

    @DefaultRes(R.string.default_myString)
    String myString();
}

And the preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <CheckBoxPreference
        android:key="myOption"
        android:defaultValue="@bool/default_myOption"
        android:title="My Option Name"/>
    <EditTextPreference
        android:key="myString"
        android:defaultValue="@string/default_myString"
        android:title="My String Option"/>
</PreferenceScreen>

Now I can define default values for both annotations and PreferenceActivity in one XML file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top