2008年8月11日 星期一

關於 Resource ID 的兩、三事

How to get a resource ID value by its name?

在 Android 中,只要你將一個圖檔 (例如 flag.png) 放入到 res/drawable 目錄中,Eclipse 就會自動幫你為這圖檔產生個 ID 名和值 (ID 名和檔案名是相同的,在此例就是 R.drawable.flag),並定義在 R.java 中,就像下面這個 R.java 範例。

接下來,要得到這圖檔的 Drawable 物件,通常你會用下面這個方式:

Drawable dw = getResources().getDrawable(R.drawable.flag);

不過,有時候,你可能會放好幾個圖檔 (例如 flag1.png ~ flag10.png),而且你想用最少的程式碼,得到這些圖檔的 Drawable 物件。這時,採用上述方法就顯得不可行。因為,這些圖檔的 ID 值,是自動編出來的,你不曉得這些值。因此,你需要一個由 ID 名,來得到 ID 值的方法。getResources().getIdentifier() 就是用在此的函式。不過,這個函式的用法有些麻煩。底下是這函式的用法說明:

public int getIdentifier(String name, String defType, String defPackage) Return a resource identifier for the given resource name. A fully qualified resource name is of the form "package:type/entry". The first two components (package and type) are optional if defType and defPackage, respectively, are specified here.

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.
Parameters
name The name of the desired resource.
defType Optional default resource type to find, if "type/" is not included in the name. Can be null to require an explicit type.
defPackage Optional default package to find, if "package:" is not included in the name. Can be null to require an explicit package.

就以剛剛舉的 flag.png 為例,你可以用:

到這,你應該知道要如何取得 flag1.png ~ flag10.png 的 Drawable 物件了,程式碼如下:

沒有留言:

張貼留言