简体   繁体   中英

How to change colors in an android app?

I want to change colors in my options menu for color blind people, I was thinking of having two strings.xml files and switch between them on button press. What is the proper way of changing colors of ImageButton that has colors declared in strings.xml ?

final Switch colorsChange= (Switch) findViewById(R.id.switch_colors);
    colorsChange.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // Color blind friendly colors here

            } else {
                // Normal RGB colors here
                getResources().getColor(R.color.defaultColors);
            }
        }
    });

I want to carry these settings across all activities if possible

button.setColor(Color.RED); or you can using button.setColor(code color);

You should declare colors in colors.xml

But still, In string.xml you should declare <string name="red">#ff0000</string>

ImageButton.setBackgroundColor(Color.parseColor(getString(R.string.red));//if using string.xml
or
ImageButton.setBackgroundColor(ContextCompat.getColor(mContext, R.color.red));//if using colors.xml

Or, alternatively:

ImageButton.setBackgroundColor(Color.RED); // From android.graphics.Color

Or, for more pro skills:

ImageButton.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB

Documentation

You should define color in color.xml (in "values" directory)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="color_name">#e6e6e6</color>
</resources>

and reference to it:

  1. In xml file:

    @color/color_name

  2. In Java class:

    getResources().getColor(R.color.color_name);

  • Add colors you want into your resources
  • Give action to your button using android:onClick="methodName"
  • In your java method get the color by using getResources().getColor(R.color.idname);

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