Skip to content

Commit bb2a0c8

Browse files
committed
Add cache for color attr
1 parent 223fd82 commit bb2a0c8

File tree

2 files changed

+34
-3
lines changed
  • app/src/main/java/omega_r/com/omegatypesexample
  • omegatypes/src/main/java/com/omega_r/libs/omegatypes

2 files changed

+34
-3
lines changed

app/src/main/java/omega_r/com/omegatypesexample/MainActivity.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ class MainActivity : BaseActivity() {
2929
)
3030
text.applyTo(exampleTextView) // or exampleTextView.setText(text)
3131

32-
val list = listOf(Text.from("1"), Text.from("2"), Text.from("3"))
32+
val list = listOf(Text.from("1", TextStyle.color(Color.fromAttribute(R.attr.colorAccent))), Text.from("2", TextStyle.color(Color.fromAttribute(R.attr.colorAccent))), Text.from("3"))
3333

3434
title = list.join(",", postfix = ".").getCharSequence(this)
3535

omegatypes/src/main/java/com/omega_r/libs/omegatypes/Color.kt

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@ package com.omega_r.libs.omegatypes
22

33
import android.content.Context
44
import android.content.res.ColorStateList
5+
import android.content.res.Resources
56
import android.os.Build
7+
import android.util.SparseIntArray
68
import android.util.TypedValue
79
import java.io.Serializable
10+
import java.util.*
811

912

1013
/**
@@ -98,9 +101,37 @@ abstract class Color : Serializable {
98101

99102
class AttrThemeColor(private val attrInt: Int) : Color() {
100103

101-
override fun getColorInt(context: Context): Int {
104+
companion object {
105+
106+
private val cache = WeakHashMap<Resources.Theme, SparseIntArray>()
107+
108+
}
109+
110+
private fun extractColor(theme: Resources.Theme): Int {
102111
return TypedValue().run {
103-
if (context.theme.resolveAttribute(attrInt, this, true)) data else 0
112+
if (theme.resolveAttribute(attrInt, this, true)) data else 0
113+
}
114+
}
115+
116+
override fun getColorInt(context: Context): Int {
117+
118+
val theme = context.theme
119+
120+
val sparseIntArray = cache[theme]
121+
122+
return sparseIntArray?.indexOfKey(attrInt)?.run {
123+
if (this >= 0) {
124+
sparseIntArray.valueAt(this)
125+
} else {
126+
extractColor(theme).apply {
127+
sparseIntArray.put(attrInt, this)
128+
}
129+
}
130+
} ?: SparseIntArray().run {
131+
cache[theme] = this
132+
extractColor(theme).apply {
133+
put(attrInt, this)
134+
}
104135
}
105136
}
106137

0 commit comments

Comments
 (0)