3

目前我只是使用 CheckBoxPreference 来激活/停用声音。声音是从原始资源播放的。

现在我想用 RingtonePreference 替换这个 CheckBoxPreference,但是我的资源中的自定义声音应该是默认声音,并且可以从 ringtonepreference 中选择。

我怎样才能做到这一点?

4

1 回答 1

2

我写了一个适合我需要的偏好类,在这里也许它会帮助其他人:

 public class SoundPreference extends ListPreference implements
            PreferenceManager.OnActivityResultListener, OnPreferenceChangeListener {

    private NotificationPrefs mAct;

    public SoundPreference(NotificationPrefs act) {
            super(act);
            mAct = act;
            setEntries(new String[] { "Silent",
                            "Custom",
                           "Picker" });
            setEntryValues(new String[] { "silent", "custom", "picker" });

            setOnPreferenceChangeListener(this);
    }

    @Override
    public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
            if (data != null) {
                    Uri uri = data
                                    .getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
                    if (uri != null) {
                            persistString(uri.toString());
                            return true;
                    }
            }
            return false;
    }

    @Override
    public void setValue(String value) {

            List<CharSequence> vals = new ArrayList<CharSequence>(
                            Arrays.asList(getEntryValues()));
            if (!vals.contains(value)) {
                    List<CharSequence> ents = new ArrayList<CharSequence>(
                                    Arrays.asList(getEntries()));
                    Ringtone r = RingtoneManager.getRingtone(getContext(),
                                    Uri.parse(value));
                    String name = r.getTitle(getContext());
                    vals.add(value);
                    ents.add(name);

                    this.setEntries(ents.toArray(new CharSequence[ents.size()]));
                    this.setEntryValues(vals.toArray(new CharSequence[vals.size()]));

            }
            super.setValue(value);
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
            if ("picker".equals(newValue)) {

                    Intent i = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
                    i.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
                    i.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
                    Intent chooserIntent = Intent.createChooser(i, getContext()
                                    .getString(R.string.sound));
                    mAct.startActivityForResult(chooserIntent, 0);
                    mAct.setActivityResultListener(this);
                    return false;
            }

            return true;

    }
 }
于 2013-07-25T09:40:25.073 回答