Prabha Karan
Prabha Karan

Reputation: 1329

How to implement functions for SwitchPreference,List Preference?

I have designed the setting page by using preference screen but i dont't know how to implement the functions in SwitchPreference and list preference.How to implement the condition by shared preference.

 android.app.FragmentManager fragmentManager = getFragmentManager();
    android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(android.R.id.content,new PreferenceFragments());
    fragmentTransaction.commit();

The above code is for fragment implementation in settings activity.

The below code is preference fragment

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preference);
    Preference preference = (Preference)findPreference("General_key");
    preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {

            return false;
        }
    });

}

The preference screen is preference.xml

 <SwitchPreference
        android:title="Auto Record"
        android:summary="Automatic Start Recording"
        android:key="General_key"
        ></SwitchPreference>
 <ListPreference
    android:title="Recording Format(Mp3)"
    android:summary="Select a Recording Format"
    android:entries="@array/listEntries"
    android:entryValues="@array/listEntriesValues"
    android:key="record_format_key"
    ></ListPreference>

This is my components in preference screen.How to implement the switch on and off condition by using shared preference .

Upvotes: 0

Views: 751

Answers (1)

aborocz
aborocz

Reputation: 199

You can implement it the same way as you did at the ListPreference. You need to set the android:entries and android:entryValues.

For example:

preferences.xml

<SwitchPreference
 android:title="Auto Record"
 android:summary="Automatic Start Recording"
 android:entries="@array/record_switch_pref_entries"
 android:entryValues="@array/record_switch_pref_values"
 android:key="General_key"/>

arrays.xml

<string-array name="record_switch_pref_entries">
        <item>No</item>
        <item>Yes</item>
</string-array>

<string-array name="record_switch_pref_values">
        <item>0</item>
        <item>1</item>
</string-array>     

If you want to listen to value / select changes you should implement SharedPreferences.OnSharedPreferenceChangeListener and register a sharedPreferenceChangeListener in the onCreate function.

getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);    

After you can handle the changes in the onSharedPreferenceChanged function.

Upvotes: 0

Related Questions