EditIntegerPreference.kt raw
1 package io.github.domi04151309.alwayson.custom
2
3 import android.content.Context
4 import android.text.InputType
5 import android.util.AttributeSet
6 import android.util.TypedValue
7 import android.widget.Toast
8 import androidx.preference.EditTextPreference
9 import io.github.domi04151309.alwayson.R
10 import java.lang.NumberFormatException
11
12 class EditIntegerPreference : EditTextPreference {
13 constructor(
14 context: Context,
15 attrs: AttributeSet?,
16 defStyleAttr: Int,
17 defStyleRes: Int,
18 ) : super(
19 context,
20 attrs,
21 defStyleAttr,
22 defStyleRes,
23 ) {
24 setOnBindEditTextListener {
25 it.inputType = InputType.TYPE_CLASS_NUMBER
26 }
27 }
28
29 constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : this(
30 context,
31 attrs,
32 defStyleAttr,
33 0,
34 )
35
36 constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, getAttr(context))
37
38 @Suppress("unused")
39 constructor(context: Context) : this(context, null)
40
41 override fun getPersistedString(defaultReturnValue: String?): String {
42 val returnValue = defaultReturnValue ?: "0"
43 val value: Int = Integer.parseInt(returnValue)
44 return getPersistedInt(value).toString()
45 }
46
47 override fun persistString(value: String): Boolean {
48 val intValue: Int
49 try {
50 intValue = Integer.parseInt(value)
51 } catch (e: NumberFormatException) {
52 Toast.makeText(context, R.string.pref_int_failed, Toast.LENGTH_LONG).show()
53 return false
54 }
55 return persistInt(intValue)
56 }
57
58 companion object {
59 fun getAttr(context: Context): Int {
60 val value = TypedValue()
61 context.theme.resolveAttribute(
62 androidx.preference.R.attr.editTextPreferenceStyle,
63 value,
64 true,
65 )
66 return if (value.resourceId != 0) {
67 androidx.preference.R.attr.editTextPreferenceStyle
68 } else {
69 android.R.attr.editTextPreferenceStyle
70 }
71 }
72 }
73 }
74