1+ package org.fossify.clock.views
2+
3+ import android.content.Context
4+ import android.text.SpannableString
5+ import android.text.Spanned
6+ import android.text.style.RelativeSizeSpan
7+ import android.util.AttributeSet
8+ import android.widget.TextClock
9+ import androidx.annotation.AttrRes
10+ import org.fossify.clock.extensions.config
11+ import java.text.DateFormatSymbols
12+
13+ private const val AM_PM_SCALE = 0.4f
14+
15+ class MyTextClock @JvmOverloads constructor(
16+ context : Context ,
17+ attrs : AttributeSet ? = null ,
18+ @AttrRes defStyleAttr : Int = android.R .attr.textViewStyle,
19+ ) : TextClock(context, attrs, defStyleAttr) {
20+
21+ private val amPmStrings by lazy {
22+ DateFormatSymbols .getInstance(
23+ resources.configuration.locales[0 ]
24+ ).amPmStrings
25+ }
26+
27+ private var reenter = false
28+
29+ override fun setText (text : CharSequence? , type : BufferType ? ) {
30+ if (reenter) {
31+ super .setText(text, type)
32+ return
33+ }
34+
35+ if (context.config.use24HourFormat || text.isNullOrEmpty()) {
36+ super .setText(text, type)
37+ return
38+ }
39+
40+ val full = text.toString()
41+ var index = - 1
42+ var amPmString: String? = null
43+ for (s in amPmStrings) {
44+ if (s.isNotEmpty()) {
45+ val i = full.indexOf(s, ignoreCase = true )
46+ if (i != - 1 ) {
47+ index = i
48+ amPmString = s
49+ break
50+ }
51+ }
52+ }
53+
54+ if (index != - 1 && amPmString != null ) {
55+ val spannable = SpannableString (text)
56+ spannable.setSpan(
57+ RelativeSizeSpan (AM_PM_SCALE ),
58+ index - 1 , // including the space before AM/PM
59+ index + amPmString.length,
60+ Spanned .SPAN_EXCLUSIVE_EXCLUSIVE
61+ )
62+ reenter = true
63+
64+ try {
65+ super .setText(spannable, type ? : BufferType .SPANNABLE )
66+ } finally {
67+ reenter = false
68+ }
69+ } else {
70+ super .setText(text, type)
71+ }
72+ }
73+ }
0 commit comments