Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A custom TimePicker preference.
package black.old.spacedrepetitionowl
import android.content.Context
import android.util.AttributeSet
import androidx.preference.DialogPreference
// This class is used in our preference where user can pick a time for notifications to appear.
// Specifically, this class is responsible for saving/retrieving preference data.
class TimepickerPreference(context: Context?, attrs: AttributeSet?) : DialogPreference(context, attrs) {
// Get saved preference value (in minutes from midnight, so 1 AM is represented as 1*60 here
fun getPersistedMinutesFromMidnight(): Int {
return super.getPersistedInt(DEFAULT_MINUTES_FROM_MIDNIGHT)
}
// Save preference
fun persistMinutesFromMidnight(minutesFromMidnight: Int) {
super.persistInt(minutesFromMidnight)
notifyChanged()
}
override fun onSetInitialValue(defaultValue: Any?) {
super.onSetInitialValue(defaultValue)
summary = minutesFromMidnightToHourlyTime(getPersistedMinutesFromMidnight())
}
// Mostly for default values
companion object {
// By default we want notification to appear at 9 AM each time.
private const val DEFAULT_HOUR = 9
const val DEFAULT_MINUTES_FROM_MIDNIGHT = DEFAULT_HOUR * 60
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.