ilyassavli
ilyassavli

Reputation: 71

Android - Setting the background of TextView programmatically according to Dark and Light Mode Themes

I have an app with themes (Dark and Light Mode Theme). And want to set background of TextView programmatically.

But the problem is, when I change the color, and change the app theme to Dark Mode then the color has not been changed. It should changed according to Theme Settings.

txtTitle.setBackgroundColor(resources.getColor(R.color.black))

Not working, just black background shows

Upvotes: 0

Views: 421

Answers (1)

Daniel Knauf
Daniel Knauf

Reputation: 589

your backgroundColor does not change because you always set it to R.color.black despite the current theme. To be theme-sensitive you must create a color resource which is defined for light and dark mode.

Inside your res folder you must create a values folder for night mode values-night.

In both you define a color resource which is set to the TextView.

Light mode

<resources>
   <color name="text_background">@android:color/black</color>
</resources>

Dark mode

<resources>
   <color name="text_background">@android:color/white</color>
</resources>

In code

txtTitle.setBackgroundColor(resources.getColor(R.color.text_background))

Upvotes: 1

Related Questions