在用RingtonePreference显示副标题 summary,如果不实时更新副标题,即不实现OnPreferenceChangeListener接口时,系统会自动保存你所选择的提示音。如果需要实时更新副标题,必须实现OnPreferenceChangeListener接口,但在接口里需要手动保存所选的铃声,少说费话,代码如下,注意红色代码:
SettingsRing .java
import android.app.ActionBar;
import android.app.Activity;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.RingtonePreference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
public class SettingsRing extends Activity {
// private ListView mListView = null;
// private ArrayAdapter mAdapter;
// private boolean mCheckedItem[];
// private SystemConfig mConfig;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new PrefsFragement()).commit(); //显示PreferenceFragment界面
}
public static class PrefsFragement extends PreferenceFragment implements
OnPreferenceChangeListener {
private static final String KEY_RING_TONE = "ringtone";
private RingtonePreference mRingTone;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
mRingTone = (RingtonePreference) findPreference(KEY_RING_TONE);
Uri uri = Uri.parse(mRingTone.getSharedPreferences().getString(
KEY_RING_TONE, ""));
mRingTone.setSummary(getRingtonName(uri));
mRingTone.setOnPreferenceChangeListener(this);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// TODO Auto-generated method stub
if (preference == mRingTone) {
preference.setSummary(getRingtonName(Uri.parse(newValue.toString())));
// 此处必须加上,否则不会保存
SharedPreferences sp = preference.getPreferenceManager().getSharedPreferences();
sp.edit().putString(preference.getKey(), newValue.toString()).commit();
}
return false;
}
// 获取提示音名称
public String getRingtonName(Uri uri) {
Ringtone r = RingtoneManager.getRingtone(getActivity(), uri);
return r.getTitle(getActivity());
}
}
preference.xml
android:key="ringtone"
android:showDefault="true"
android:showSilent="true"
android:title="提示音" />