How to override getResources in Activity

纵然是瞬间 提交于 2020-05-13 09:33:30

问题


I've tried to extend Resources class, so i can override getString(int id) methode, so can do some effects to every String needed within my Activity, here i provide some my code:

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) + " $$";
    }

}

and in my Activity :

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;
    }

but there's error shown on Runtime:

Caused by: java.lang.NullPointerException

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

and it points to:

super.getWindowManager().getDefaultDisplay().getMetrics(metrics);

回答1:


i solved it:

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

        return customResource;
    }

all of that, to add some text to all Strings needed in XML, when i use setContentView(R.layout.sample) , but it did not work :(



来源:https://stackoverflow.com/questions/6889633/how-to-override-getresources-in-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!