何时以及为什么要使用getResources()?

Pet*_*tai 5 resources android

我刚刚开始使用Android开发和玩游戏.

getResources()文档说它会[r]eturn a Resources instance for your application's package.

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

例如,my_stringres/values/strings.xml以下位置检索:

<!-- strings.xml -->
...
<string name="my_string">This is my string</string>
...
Run Code Online (Sandbox Code Playgroud)

您可以使用这两种方式

第一种方式:

// MyActivity.java //  
... 
// No need to use getResources()
String msg = getString(R.string.my_string);
...
Run Code Online (Sandbox Code Playgroud)

第二种方式:

// 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);
...
Run Code Online (Sandbox Code Playgroud)

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

ble*_*enm 4

资源有许多我们可能需要的辅助方法。

R.id、R.drawable 都返回 android 在构建时分配的动态 int。假设我们有一个要求,需要根据名称访问国家标志图像。

如果我们的图像名称为 us.png 并且我们的值是“us”。处理它的两种方法是

if(countryName.equals("us")){
    imageview.setImageRsource(R.drawable.us);
}
Run Code Online (Sandbox Code Playgroud)

或者

Resources res = getResources();
int imageId = res.getIdentifier(getIdentifier(countryName, "drawable"
        ,"com.myapp");
imageview.setImageRsource(imageId);
Run Code Online (Sandbox Code Playgroud)

第二种方法将是最佳选择,尤其是当有超过 50 个国家/地区时,否则您最终会得到很长的 if-else 或 switch 语句。

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

res.getAssets().open(YOUR FILE);
Run Code Online (Sandbox Code Playgroud)

资源实例也可以传递给其他类文件来访问资源。这些是您可以使用它的一些场景。