如何只调用ListPreference对话框?

时间:2015-11-28 21:21:22

标签: android

在偏好活动中,我支持从xml列出首选项

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
  <ListPreference
      android:key="lang"
      android:title="@string/LangTitle"
      android:summary="@string/LangSummary"
      android:defaultValue="en"

      android:entries="@array/entries_lang"
      android:entryValues="@array/entryvalues_lang"
      android:dialogTitle="@string/LangDialogTitle"
      />
</PreferenceScreen>

首先显示设置为tittle和description的首选项屏幕。当我点击它时,会显示带有可用选项的对话框 有没有办法只显示该对话框?是否直接打电话给它?

2 个答案:

答案 0 :(得分:5)

对于所有可能需要它的人:没有直接电话,但它可以很容易地重建。在DialogFragment之后创建与ListPreference

完全相同的对话框
public class LanguagePreferenceDialog extends DialogFragment {
  private CharSequence[] mEntries;
  private CharSequence[] mEntryValues;
  private String mValue;
  private boolean mValueSet;
  SharedPreferences prefs;
  private int mClickedDialogEntryIndex;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    mEntries = getResources().getStringArray(R.array.entries_lang);
    mEntryValues = getResources().getStringArray(R.array.entryvalues_lang);
    mValue = prefs.getString("lang", "en");
  }

  @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
    dialog.setTitle(getString(R.string.LangDialogTitle));
    dialog.setPositiveButton(null, null);
    mClickedDialogEntryIndex = getValueIndex();
    dialog.setSingleChoiceItems(mEntries, mClickedDialogEntryIndex, selectItemListener);
    return dialog.create();
  }

  private int getValueIndex() {
    return findIndexOfValue(mValue);
  }

  public int findIndexOfValue(String value) {
    if (value != null && mEntryValues != null) {
      for (int i = mEntryValues.length - 1; i >= 0; i--) {
        if (mEntryValues[i].equals(value)) {
          return i;
        }
      }
    }
    return -1;
  }

  DialogInterface.OnClickListener selectItemListener = new DialogInterface.OnClickListener() {

    @Override public void onClick(DialogInterface dialog, int which) {
      if (mClickedDialogEntryIndex != which) {
        mClickedDialogEntryIndex = which;
        mValue = mEntryValues[mClickedDialogEntryIndex].toString();
        prefs.edit().putString("lang", mValue).commit();
      }
      dialog.dismiss();
    }
  };
}

答案 1 :(得分:0)

我们无法直接调用ListPreference而不会泄露首选项xml文件。 Preference应始终位于PreferenceScreen内。我们必须给整个xml文件充气,以便在UI上使用它们。您必须显示一个包含ListView的对话框。