第一种方法,参照NightDisplaySettings.java
@Override public boolean onPreferenceTreeClick(Preference preference) { if (preference == mStartTimePreference) { showDialog(DIALOG_START_TIME); return true; return super.onPreferenceTreeClick(preference); } @Override public Dialog onCreateDialog(final int dialogId) { if (dialogId == DIALOG_START_TIME || dialogId == DIALOG_END_TIME) { final Context context = getContext(); final boolean use24HourFormat = android.text.format.DateFormat.is24HourFormat(context); TextView ledValueText; SeekBar ledSeekBar; View view = LayoutInflater.from(context).inflate(R.layout.led_brightness_setting_dialog, null); AlertDialog builder = new AlertDialog.Builder(context) .setTitle("LED brightness setting") .setView(view) .create(); //builder.getWindow().setContentView(R.layout.led_brightness_setting_dialog); ledValueText = (TextView) view.findViewById(R.id.led_setting_text); ledSeekBar = (SeekBar) view.findViewById(R.id.led_setting_seekbar); ledSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); return builder; } return super.onCreateDialog(dialogId); }
android8.1中继承SettingsPreferenceFragment并在类中创建dialog的时候,遇到SettingsDialogFragmentjava.lang.IllegalStateException: Dialog must provide a metrics category异常。
需要override getDialogMetricsCategory,比如:
@Override public int getDialogMetricsCategory(int dialogId) { switch (dialogId) { case DIALOG_START_TIME: return MetricsEvent.DIALOG_NIGHT_DISPLAY_SET_START_TIME; case DIALOG_END_TIME: return MetricsEvent.DIALOG_NIGHT_DISPLAY_SET_END_TIME; default: return 0; } }