Skip to content

Instantly share code, notes, and snippets.

@Audhil
Created June 30, 2021 17:08
Show Gist options
  • Save Audhil/c2eff976b96eca770c5c5105517e60a5 to your computer and use it in GitHub Desktop.
Save Audhil/c2eff976b96eca770c5c5105517e60a5 to your computer and use it in GitHub Desktop.
Dynamically changing(Overriding) - color from colors.xml
class DynamicHomeFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val color2 = requireActivity().application.resources.getColor(R.color.your_special_color, null) // returns Color.GREEN
binding.content.ll3.setBackgroundColor(color2)
}
}
class AppThemeRes(
original: Resources
) : Resources(original.assets, original.displayMetrics, original.configuration) {
@Throws(NotFoundException::class)
override fun getColor(id: Int): Int {
return getColor(id, null)
}
@Throws(NotFoundException::class)
override fun getColor(id: Int, theme: Theme?): Int {
return when (getResourceEntryName(id)) {
"your_special_color" -> {
println("yup: your_special_color got called")
Color.GREEN
}
"colorPrimary" -> {
println("yup: colorPrimary got called")
Color.RED
}
else -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
super.getColor(id, theme)
} else
super.getColor(id)
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--some color-->
<color name="your_special_color">#EB485F</color>
</resources>
class MyApp : Application() {
private var appThemeRes: AppThemeRes? = null
override fun getResources(): Resources {
if (appThemeRes == null)
appThemeRes = AppThemeRes(super.getResources())
return appThemeRes!!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment