简体   繁体   English

如何在Android应用中更改颜色?

[英]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. 我想在色盲人的选项菜单中更改颜色,当时我想拥有两个strings.xml文件,并在按下按钮时在它们之间切换。 What is the proper way of changing colors of ImageButton that has colors declared in strings.xml ? 更改具有在strings.xml中声明的颜色的ImageButton颜色的正确方法是什么?

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); button.setColor(Color.RED); or you can using button.setColor(code color); 或者您可以使用button.setColor(code color);

You should declare colors in colors.xml 您应该在colors.xml中声明颜色

But still, In string.xml you should declare <string name="red">#ff0000</string> 但是,仍然需要在string.xml中声明<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) 您应该在color.xml中定义颜色(在“值”目录中)

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

and reference to it: 并引用它:

  1. In xml file: 在xml文件中:

    @color/color_name @ color / color_name

  2. In Java class: 在Java类中:

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

  • Add colors you want into your resources 在资源中添加所需的颜色
  • Give action to your button using android:onClick="methodName" 使用android:onClick="methodName"对按钮进行操作
  • In your java method get the color by using getResources().getColor(R.color.idname); 在您的java方法中,使用getResources().getColor(R.color.idname);获得颜色getResources().getColor(R.color.idname);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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