Reputation: 31
I am doing an app using the PreferenceFragmentCompat, and i need to add an option TimePicker to my prefs, but my app crashes when i click on this option.
Here's my code:
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) {
}
}
And finally here's my 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>
What am i doing wrong? is there any simple method to show time picker from PreferenceFragment?
Upvotes: 0
Views: 171
Reputation: 514
You need to extend DialogPreference for the preference that hosts the dialog, and DialogPreferenceFragmentCompat, to create the dialog that contains the timepicker - I would recommend reading this medium post - it details setting up a time picker dialog.
Upvotes: 1