上下文或活动之外的 getString [英] getString Outside of a Context or Activity

查看:29
本文介绍了上下文或活动之外的 getString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 R.string 非常适合将硬编码字符串保留在我的代码之外,我想继续在与我的应用程序中的模型一起工作的实用程序类中使用它产生输出.例如,在这种情况下,我从活动之外的模型生成电子邮件.

I've found the R.string pretty awesome for keeping hardcoded strings out of my code, and I'd like to keep using it in a utility class that works with models in my application to generate output. For instance, in this case I am generating an email from a model outside of the activity.

是否可以在 ContextActivity 之外使用 getString?我想我可以传入当前的活动,但这似乎没有必要.如果我错了,请纠正我!

Is it possible to use getString outside a Context or Activity? I suppose I could pass in the current activity, but it seems unnecessary. Please correct me if I'm wrong!

我们可以在不使用Context的情况下访问资源吗?

Can we access the resources without using Context?

推荐答案

是的,我们可以不使用`Context`来访问资源

您可以使用:

Resources.getSystem().getString(android.R.string.somecommonstuff)

... 在您的应用程序中的任何地方,甚至在静态常量声明中.不幸的是,它仅支持系统资源.

... everywhere in your application, even in static constants declarations. Unfortunately, it supports the system resources only.

对于本地资源,请使用此解决方案.这不是微不足道的,但它确实有效.

For local resources use this solution. It is not trivial, but it works.

这篇关于上下文或活动之外的 getString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆