Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android switchpreference how can i set the switch preference default value?

I have a switch preference and want it to be defaulted "ON"... in the xml,

<SwitchPreference
        android:defaultValue="true"
        android:key="PromoNotificationOnOff"
        android:title="@string/Snotification_enable" />

and in class,

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.settings);


}

why isn't it working? What is missing? Thanks!!

like image 289
MW_hk Avatar asked Mar 25 '13 03:03

MW_hk


People also ask

How do I set default preferences?

Open your phone's Settings app. Default apps. Tap the default that you want to change. Tap the app that you want to use by default.

Where can I find preference in Android Studio?

A Preference is the basic building block of the Preference Library. A settings screen contains a Preference hierarchy. You can define this hierarchy as an XML resource, or you can build a hierarchy in code. The sections below describe how to build a simple settings screen using the AndroidX Preference Library.

What are preferences in Android?

Preferences in Android are used to keep track of application and user preferences. In our case, we can modify the SharedPreference instance in our case using the edit() and use the putInt(String key, int newVal) We increased the count for our application that presist beyond the application and displayed accordingly.


2 Answers

In your MainActivity onCreate method add this line

PreferenceManager.setDefaultValues(this, R.xml.settings, false);  

You can read about it at http://developer.android.com/reference/android/preference/PreferenceManager.html#setDefaultValues(android.content.Context, int, boolean)

like image 74
Hoan Nguyen Avatar answered Oct 21 '22 23:10

Hoan Nguyen


The code is correct just use switchPreferenceCompact instead of SwitchPreference

     <SwitchPreferenceCompat
        app:key="promoNofitficationOnOff"
        app:summaryOff="@string/notification_summary_off"
        app:summaryOn="@string/notification_summary_on"
        app:defaultValue="true"
        app:title="@string/promo_notification_title" />
like image 36
Ayia Avatar answered Oct 21 '22 23:10

Ayia