PreferenceFragmentCompat 内的 TimePicker(DialogFragment)

TimePicker(DialogFragment) inside the PreferenceFragmentCompat

我正在使用 PreferenceFragmentCompat 做一个应用程序,我需要向我的首选项添加一个选项 TimePicker,但是当我点击这个选项时我的应用程序崩溃了。

这是我的代码:

时间偏好:

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.text.format.DateFormat;

import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;

import java.util.Calendar;


public class TimePreference extends DialogFragment {

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(), hour, minute, DateFormat.is24HourFormat(getActivity()));
    }
}

设置片段:

import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;

import com.sstu.studentcalendar.R;
import com.sstu.studentcalendar.Service.TimePreference;

public class SettingsFragment extends PreferenceFragmentCompat{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.prefs);
        Preference preference = (Preference)getPreferenceManager().findPreference("timeset");
        if (preference != null) {
            preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference arg0) {
                    DialogFragment timePicker = new TimePreference();
                    timePicker.show(getFragmentManager(), "time picker");
                    return true;
                }
            });
        }
    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {

    }
}

最后是我的 prefs.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="match_parent" android:layout_width="match_parent">
    <CheckBoxPreference
        android:key="notificationBoolean"
        android:summary="Включить напоминания"
        android:title="Напоминания">
    </CheckBoxPreference>
    <Preference android:title="Timepicker" android:key="timeset"/>
</PreferenceScreen>

我做错了什么?有什么简单的方法可以从 PreferenceFragment 中显示时间选择器吗?

您需要为托管对话框的首选项扩展 DialogPreference 和 DialogPreferenceFragmentCompat,以创建包含时间选择器的对话框 - 我建议阅读这篇 medium post - 它详细介绍了时间选择器对话框的设置。