本文介绍了如何在Activity中覆盖getResources的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试扩展Resources类,因此我可以覆盖getString(int id)方法,因此可以对Activity中所需的每个String产生一些影响,这里提供一些代码:

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

}

以及在我的活动中:

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

Runtime上显示错误:

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

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

它指向:

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

推荐答案

我解决了它:

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

        return customResource;
    }

所有这些,当我使用setContentView(R.layout.sample)时,向XML所需的所有Strings中添加一些文本,但是它不起作用:(

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 :(

这篇关于如何在Activity中覆盖getResources的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:36