Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the different between getColor() and getColorStateList() in Android

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?

like image 768
Udara Abeythilake Avatar asked Nov 24 '25 09:11

Udara Abeythilake


2 Answers

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>
like image 159
A.sobhdel Avatar answered Nov 25 '25 21:11

A.sobhdel


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>
like image 35
Milan Pansuriya Avatar answered Nov 25 '25 23:11

Milan Pansuriya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!