Issue
I am trying to change the color of text in a fragment based on the currently active theme. But the app keeps crashing with the following error
android.content.res.Resources$NotFoundException: Resource ID #0xff000000
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:237)
at android.content.res.Resources.getColor(Resources.java:1059)
at android.content.Context.getColor(Context.java:677)
My code is below:
bind.scrollDate.setTextColor(view.context.getColor(if (day.date == selectedDate) R.color.white else getColorByThemeAttr(requireContext(),R.attr.txtcolor,R.color.txtcolor)))
//getting colors based on theme
private fun getColorByThemeAttr(context: Context, attr: Int, defaultColor: Int): Int {
val typedValue = TypedValue()
val theme: Resources.Theme = context.theme
val got: Boolean = theme.resolveAttribute(attr, typedValue, true)
return if (got) typedValue.data else defaultColor
}
I understand that using the right context in fragment is important, but have tried multiple variations with none working....
Any solution for this please?
Solution
So, TypedValue will not be resource id, but value. This means that you should change call to this:
a.setTextColor(if (1!=1) view.context.getColor(R.color.colorAccent) else getColorByThemeAttr(requireContext(),R.attr.txtColor,R.color.color2))
And your method to something like this:
private fun getColorByThemeAttr(context: Context, attr: Int, defaultColor: Int): Int {
val typedValue = TypedValue()
val theme: Resources.Theme = context.theme
val got: Boolean = theme.resolveAttribute(attr, typedValue, true)
return if (got) typedValue.data else context.getColor(defaultColor)
}
Answered By - Милош Којадиновић
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.