什么时候以及为什么应该使用getResources()? [英] When and why should one use getResources()?

查看:115
本文介绍了什么时候以及为什么应该使用getResources()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才刚开始使用Android开发人员并随便玩玩.

I'm just getting started with Android dev and playing around.

getResources()的文档表示它将 [r]返回应用程序包的Res​​ources实例.

在代码示例中,我已经看到它用于访问 res 中的资源,但是似乎您可以直接访问它们.

In code examples I've seen this used to access the resources in res, but it seems like you can just access them directly.

例如,从 res/values/strings.xml 中检索 my_string :

<!-- strings.xml -->
...
<string name="my_string">This is my string</string>
...

您可以使用这两种方式

第一种方式:

// MyActivity.java //  
... 
// No need to use getResources()
String msg = getString(R.string.my_string);
...

第二种方式:

// MyActivity.java //
...
// What is the point of getResources() here?
// It works but it requires "import android.content.res.Resources;" and is longer
Resources the_resources = this.getResources();
String msg = the_resources.getString(R.string.my_string);
...

那么,什么时候需要您使用 getResources()来访问资源?似乎没有必要,或者它是隐式调用,还是必须它被称为访问某些其他类型的资源或以其他方式访问资源?

So, when would you be required to use getResources() to access a resource? Seems like it is not necessary, or is it being call implicitly, or must it be called to access certain other types of resources or to access resources in other ways?

推荐答案

资源有许多我们可能需要的帮助方法.

Resources have many helper methods that we may require.

R.id,R.drawable全部返回在构建期间由android分配的动态int.假设有一个要求,我们需要根据其名称访问coutries标志图像.

R.id, R.drawable all return dynamic int assigned by android during build time. Suppose we have a requirement where we require to access a coutries flag image based on its name.

如果我们的图像名称为us.png,而我们的值为'us'.处理它的2种方法是

If we have image name as us.png and the value we have is 'us'. The 2 ways to handle it are

if(countryName.equals("us")){
    imageview.setImageRsource(R.drawable.us);
}

OR

Resources res = getResources();
int imageId = res.getIdentifier(getIdentifier(countryName, "drawable"
        ,"com.myapp");
imageview.setImageRsource(imageId);

第二种方法将成为一种选择,特别是当有50多个国家/地区时,否则您将得到很长的if-else或switch语句.

The second method will be the way to go especially when there are more than 50 countries or you will end up with a very long if-else or switch statement.

当您需要访问Assets文件夹中的内容时,也会使用资源对象

The resources object is also used when you need to access the contents in the Assets folder

res.getAssets().open(YOUR FILE);

资源实例也可以传递给其他类文件以访问资源.这些是您可以使用的一些方案.

Resource instance can also be passed to other class files to access the the resources. These are some of the scenarios that you can use it for.

这篇关于什么时候以及为什么应该使用getResources()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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