Skip to content

Instantly share code, notes, and snippets.

@hafizrahman
Created September 18, 2020 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hafizrahman/58529caac67cd8fefa17992de0877093 to your computer and use it in GitHub Desktop.
Save hafizrahman/58529caac67cd8fefa17992de0877093 to your computer and use it in GitHub Desktop.
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