/* * Copyright (c) 2015 Jonas Kalderstam. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nononsenseapps.notepad.util; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.preference.ListPreference; import android.preference.Preference; import android.preference.RingtonePreference; import android.support.annotation.NonNull; import android.text.TextUtils; import com.nononsenseapps.notepad.R; /** * Utilities for Preferences */ public class PreferenceHelper { /** * A preference value change listener that updates the preference's summary * to reflect its new value. Handles ringtone preferences and list preferences * specially. */ public static final Preference.OnPreferenceChangeListener sSummaryUpdater = new Preference .OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(@NonNull Preference preference, @NonNull Object value) { String stringValue = value.toString(); if (preference instanceof ListPreference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. ListPreference listPreference = (ListPreference) preference; int index = listPreference.findIndexOfValue(stringValue); // Set the summary to reflect the new value. preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null); } else if (preference instanceof RingtonePreference) { // For ringtone preferences, look up the correct display value // using RingtoneManager. if (TextUtils.isEmpty(stringValue)) { // Empty values correspond to 'silent' (no ringtone). preference.setSummary(R.string.silent); } else { Ringtone ringtone = RingtoneManager.getRingtone(preference.getContext(), Uri .parse(stringValue)); if (ringtone == null) { // Clear the summary if there was a lookup error. preference.setSummary(null); } else { // Set the summary to reflect the new ringtone display // name. String name = ringtone.getTitle(preference.getContext()); preference.setSummary(name); } } } else { // For all other preferences, set the summary to the value's // simple string representation. preference.setSummary(stringValue); } return true; } }; }