简体   繁体   中英

How to change a color value in android via java code

I want to change the hex color value of a color variable and colorAccent color defined in the colors.xml file by MainActivity.java code.

What code should I write in the java file inside a method or a switch or if/else statement to change it?

在此处输入图片说明

You should use themes and styles for changing color values. See: Styles and Themes

Basically, you should declare the color in styles.xml:

<style name="GreenText" parent="TextAppearance.AppCompat">
    <item name="android:textColor">#00FF00</item>
</style>

<style name="RedText" parent="TextAppearance.AppCompat">
    <item name="android:textColor">#ff0000</item>
</style>

Then declare which theme to use in onCreate (before setContentView()):

 switch (theme) {
     case 1:
         setTheme(R.style.Green);
         break;
     case 2:
         setTheme(R.style.Red);
         break;
 }

Edit : You can change the theme during onCreate() only - If you want to change it afterwards, during runtime, you will have to recreate your activity by calling recreate()

Unfortunately all color values (and other resources) inside the resources directory are hardcoded as static final ints. This means there is no way to change the values at runtime. You can however use one of the previously suggested solutions or have a look at this excellent

here's exaplained

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM