覆盖'style.xml'以编程方式更改Android中的颜色

时间:2019-07-02 08:38:49

标签: android xml colors resources themes

正如标题所示,我需要根据自己的喜好更改Android布局的颜色。 我完全知道它们是静态变量,但是正如您从代码中看到的那样,我试图覆盖输入的值,但是即使找到该值,也不会对其进行更新或修改。 实用程序类仅是示例。

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;


public class ResUtils extends Resources {


private Context context;

public ResUtils(Resources original, Context context) {
    super(original.getAssets(), original.getDisplayMetrics(), original.getConfiguration());
    this.context = context;
}


@Override
public int getColor(int id) throws NotFoundException {
    int color = getColor(id, context.getTheme());
    return color;
}

@Override
public int getColor(int id, Theme theme) throws NotFoundException {
    int example = Color.MAGENTA;
    int retColor = 0;
    if (example != 0) {
        switch (getResourceEntryName(id)) {
            case "colorPrimary":
                retColor = example;
                return retColor;
            default:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    retColor = super.getColor(id, theme);
                    return retColor;
                } else {
                    retColor = super.getColor(id);
                    return retColor;
                }

        }
    } else {
        retColor = super.getColor(id, theme);
    }
    return retColor;
    }
}

我在MainActivity中添加以下代码:

private ResUtils res;

    @Override
    public ResUtils getResources() {
        if (res == null) {
            res = new ResUtils(super.getResources(), getApplicationContext());
        }
        return res;
    }
}

这是我的主题:

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="colorPrimary">#E20612</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

这是一个简单的布局:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <corners
        android:radius="20px"/>
    <stroke
        android:width="2px"
        android:color="?colorPrimary">
    </stroke>
    <solid
        android:color="?colorPrimary"/>
</shape>

我想在MAGENTA中更新我的“ colorPrimary”(对于这种情况)...但没有任何动静!

0 个答案:

没有答案