Search code examples
androidpreferences

Android preference


I'm making a backup and restore options in my android app. Then you open the preference I want a button to backup and a button to restore. I make the button in my xml/preference.xml file like this:

<PreferenceCategory android:title="Backup">
    <Preference
        android:key="backup"
        android:title="Backup"
        android:summary="Make a backup of shows"
    />
    <Preference
        android:key="restore"
        android:title="Restore"
        android:summary="Restore shows from backup"
    />
</PreferenceCategory>

I my preference class I implements OnSharedPreferenceChangeListener, and add getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); to onResume() and getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); to OnPause().

The i implements onSharedPreferenceChanged:

  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
      // Let's do something when my counter preference value changes
      if (key.equals("backup")) {
          Toast.makeText(this, "Backup button pressed", Toast.LENGTH_SHORT).show();
      } else if (key.equals("restore")) {
          Toast.makeText(this, "Restore button pressed", Toast.LENGTH_SHORT).show();
      } 
  } 

But no toast is displayed then i press one of the buttons. I works fine on i.e. CheckBoxPreference, but i only need a button, not the checkbox. Some one who can help?


Solution

  • put your code to

    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
                                             Preference preference);
    

    method. preference here is the preference that were clicked.