我試圖根據當前的活動主題來改變片段中文本的顏色。但應用程式一直在崩潰,并出現以下錯誤
。android.content.res.Resources$NotFoundException。資源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)
我的代碼如下:
bind.scrollDate.setTextColor(view.context.getColor(if (day.date == selectedDate) R&D.getColor() date == selectedDate) R.color.white else getColorByThemeAttr(requireContext(),R.attr.txtcolor,R.color.txtcolor))
//獲得基于主題的顏色。
private fun getColorByThemeAttr(text: Context, attr: Int, defaultColor: Int)。Int {
val typedValue = TypedValue()
val 主題。資源.主題 = 背景.主題
val got: Boolean = theme.resolveAttribute(attr, typedValue, true)
return if (got) typedValue.data else defaultColor
}
我知道在片段中使用正確的背景關系是很重要的,但我嘗試了多種變化,都沒有成功....
請問有什么解決方案嗎?
uj5u.com熱心網友回復:
因此,TypedValue不會是資源ID,而是價值。這意味著你應該把呼叫改為這樣:
a.setTextColor(if (1! =1) view.context.getColor(R.color.colorAccent) else getColorByThemeAttr(requireContext(),R.attr.txtColor,R.color.color2)
而你的方法是這樣的:
你的方法是這樣的:
private fun getColorByThemeAttr(text: Context, attr: Int, defaultColor: Int)。Int {
val typedValue = TypedValue()
val 主題。資源.主題 = 背景.主題
val got: Boolean = theme.resolveAttribute(attr, typedValue, true)
return if (got) typedValue.data else context.getColor(defaultColor)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318379.html
標籤:
上一篇:從活動中呼叫一個當前可見的NavHostFragment的方法
下一篇:安卓串列視圖不能與片段作業
