Color Resource

Color Resource
A color resource in Android Studio is a way to define colors that can be reused throughout an application. These resources are typically defined in XML files and can be referenced in various parts of the app, such as layouts, styles, and themes.

Characteristics
Reusability: Color resources can be defined once and reused across multiple components, promoting consistency in design.
Maintainability: Changes to a color can be made in one place, and those changes will automatically reflect wherever the color is used.
Support for Different States: Color resources can be defined for different states (e.g., pressed, focused) using state lists.
Theming: Color resources can be easily integrated into themes, allowing for dynamic changes based on user preferences or system settings (like dark mode).

Examples
– Defining a color in res/values/colors.xml:
xml
<resources>
<color name="primaryColor">#FF6200EE</color>
<color name="secondaryColor">#FF03DAC5</color>
<color name="backgroundColor">#FFFFFF</color>
</resources>

  • Referencing a color resource in a layout XML file:
    xml
    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello, World!"
    android:textColor="@color/primaryColor" />

  • Using a color resource in Java/Kotlin code:
    java
    int color = ContextCompat.getColor(context, R.color.primaryColor);

  • Defining a color state list in res/color/color_state_list.xml:
    xml
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/secondaryColor" />
    <item android:color="@color/primaryColor" />
    </selector>

Comments