Reputation: 1213
I'm using getColor()
method to select color from resources. But I found that there is another method called getColorStateList()
. Which one is easy to use and what is the difference between them?
Upvotes: 3
Views: 1529
Reputation: 234
lets assume that you want to setBackgroundColor to a view for example a linearLayout. if you want its background color to be permanent ,you would want to use getColor() to set a certain color. but if you want its color to change on different states and events like pressed state or not pressed state you would want to set resource id of the xml file containing the code for these color change tasks.
here is what im saying in code:
linearLayout.setBackgroundColor(getResources().getColor(R.color.red);
line of code above sets the permanent color of linearLayout to red.
linearLayout.setBackgroundTintList(getResources().getColorStateList(R.drawable.layout_background));
and this single line of code above will set the background color to red when layout is pressed and white when its not pressed.
layout_background.xml :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="@color/red" />
<item android:state_pressed="false"
android:color="@color/white" />
</selector>
Upvotes: 2
Reputation: 2559
getColor() Returns a color integer associated with a particular resource ID
getColorStateList() ColorStateLists are created from XML resource files defined in the "color" subdirectory directory of an application's resource directory. The XML file contains a single "selector" element with a number of "item" elements inside. For example:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:color="@color/sample_focused" />
<item android:state_pressed="true"
android:state_enabled="false"
android:color="@color/sample_disabled_pressed" />
<item android:state_enabled="false"
android:color="@color/sample_disabled_not_pressed" />
<item android:color="@color/sample_default" />
</selector>
Upvotes: 1