1

I've created a project and added 2 buttons in activity_main.xml but they have different colors in layout preview and the actual app. How come?

enter image description here

There are 2 files under themes:

themes.xml:

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="NecklaceShowcase" parent="Theme.MaterialComponents.Light.NoActionBar" >
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>
</resources>

and themes.xml (night)

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="NecklaceShowcase">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_200</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/black</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_200</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>
</resources>
Behnawwm
  • 121
  • 2
  • 9

1 Answers1

2

The layout preview is using the theme you have set in your themes.xml file.

When you run the app the btn2 is switching to red because in your activity_main.xml it is setting its background to: halo_red_light.

I'm unable to tell why the other button is changed to grey this may have been set in your activity class.

You can read more here

COYG
  • 1,538
  • 1
  • 16
  • 31
  • So how can i use the theme and still be able to see the preview properly? – Behnawwm Mar 31 '21 at 06:42
  • @Behnawwm remove the background attribute for btn2 and this will remove the color red from the button. However, you haven't included your activity class code where I suspect you are setting a style when creating the buttons so they will replace your theme and appear grey. If you edit your post, include the activity code and notify me I will take a look. – COYG Mar 31 '21 at 16:31