PreferenceFragmentCompat中的TimePicker(DialogFragment)

时间:2019-07-13 21:36:02

标签: java android android-preferences

我正在使用PreferenceFragmentCompat做一个应用程序,我需要在我的偏好设置中添加一个选项TimePicker,但是当我单击此选项时,我的应用程序将崩溃。

这是我的代码:

TimePreference:

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()));
    }
}

SettingsFragment:

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中的时间选择器?

1 个答案:

答案 0 :(得分:0)

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