我正在使用 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) {
}
}
我究竟做错了什么?有什么简单的方法可以从 PreferenceFragment 显示时间选择器吗?
泛舟湖上清波郎朗
相关分类