如何在 Activity 中覆盖 getResources

Moh*_*san 5 resources android overriding

我试图扩展Resources类,所以我可以覆盖getString(int id)方法,所以可以对String我的每个需要的东西做一些影响Activity,在这里我提供一些我的代码:

public class CustomResource extends Resources {

    public CustomResource(AssetManager assets, DisplayMetrics metrics, Configuration config) {
        super(assets, metrics, config);
    }

    @Override
    public String getString(int id) throws NotFoundException {
        return super.getString(id) + " $$";
    }

}
Run Code Online (Sandbox Code Playgroud)

在我的活动中:

CustomResource customResource;
    @Override
    public Resources getResources() {
        if (customResource == null) {
            DisplayMetrics metrics = new DisplayMetrics();
            super.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            customResource = new CustomResource(getAssets(), metrics, super.getResources().getConfiguration());
        }
        return customResource;
    }
Run Code Online (Sandbox Code Playgroud)

但有错误显示在Runtime

引起:java.lang.NullPointerException

在 com.test.TestActivity.getResources(TestActivity.java:75)

它指出:

super.getWindowManager().getDefaultDisplay().getMetrics(metrics);
Run Code Online (Sandbox Code Playgroud)

Moh*_*san 5

找到了一个方法:

private CustomResource customResource;

@Override
    public Resources getResources() {
        if (customResource == null) {
            customResource = new CustomResource(super.getAssets(), super.getResources().getDisplayMetrics(), super
                    .getResources().getConfiguration());
        }

        return customResource;
    }
Run Code Online (Sandbox Code Playgroud)

即使在添加此资源后,它仍然不会覆盖来自 LayoutInflator 的 Strings 值(例如setContentView(R.layout.sample)