2021/January/8
If you want to get color from theme attributes, use the following steps.
Create a variable my_color and store the color from theme attributes as,
val my_color = MaterialColors.getColor(<VIEWOBJECT>, R.attr.<YOUATRRIBUTENAME>)
In place of <VIEWOBJECT>
, pass a view object where you want to use the color, (behind the scenes it's just used to get the context as <VIEWOBJECT>.getContext()
so that it can access resource i.e theme attribute values) . In place of <YOURATTRIBUTENAME>
, use the name of the atrribute that you want to access
Example 1:
If you want want to get color referenced by theme attributes from certain activity.
Create a variable that represents a view object on which you want to use the color.
Here i have a textView in my activity, i'll just reference its object inside textview
variable and pass it to the getColor
method and behind the scenes it'll use that object to just get the context, so that it can access theme attribute values
val textview: TextView = findViewById(R.id.mytextview)
val my_color = MaterialColors.getColor(textView, R.attr<YOURATTRIBUTENAME>)
Example 2 :
If you want to get color from theme attributes inside a custom view then just use,
val my_color = MaterialColors.getColor(this, R.attr.<YOUATRRIBUTENAME>)
Inside a custom view this
refers to the object of the custom view, which is in fact a view object.