我试过扩展 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) + " $$";
}
}
在我的 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;
}
但在 Runtime
上显示错误:
Caused by: java.lang.NullPointerException
at com.test.TestActivity.getResources(TestActivity.java:75)
它指向:
super.getWindowManager().getDefaultDisplay().getMetrics(metrics);
最佳答案
找到一个方法:
private CustomResource customResource;
@Override
public Resources getResources() {
if (customResource == null) {
customResource = new CustomResource(super.getAssets(), super.getResources().getDisplayMetrics(), super
.getResources().getConfiguration());
}
return customResource;
}
即使在添加了这些资源之后,它仍然不会覆盖来自 LayoutInflator 的字符串值(例如 setContentView(R.layout.sample)
)
关于android - 如何覆盖 Activity 中的 getResources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6889633/