Android:リソースIDおよびgetIdentifier()を使用してリソースIdを取得


リソースIdの概要:
私たちが普段リソースを取得するのはfindViewByIdメソッドによって行われています.例えば、onCreateメソッドではこのような文をよく使用しています.
btnChecked=(ImageView)findViewById(R.id.imgCheck);
findView ByIdは、ボタン、ラベル、ListView、ImageViewなどのlayout内のさまざまなViewオブジェクトを取得する便利な方法です.名前の通りintパラメータ:リソースidが必要です.
リソースidは非常に役に立ちます.Androidは、resディレクトリの下にあるリソースごとにidを自動的に割り当て、様々なピクチャファイル、xml文の「@+id」オブジェクトを含む.resのサブディレクトリは、drawable-xxxx、layout、values、anim、xml、row、colorなど、常に固定されています.
Androidはresディレクトリの下のすべてのリソースにidを割り当てます.その主な割り当て原則は:
drawableのピクチャファイルは、常にファイルごとにリソースidを1つずつ使用します.
Xmlファイルにはandroid:id="@+id/xxx"を使用するviewごとに未使用のリソースidが割り当てられます.
getIdentifier()を使用してリソースIdを取得するには、次の手順に従います.
関数のプロトタイプ:
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.
Parametersname 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.
Returnsint The associated resource identifier. Returns 0 if no such resource was found. (0 is not a valid resource ID.)
1>方式1
Resources resources = context.getResources();
int indentify = resources.getIdentifier(org.loveandroid.androidtest:drawable/icon”,null,null);
if(indentify>0){
icon = resources.getDrawable(indentify);

最初のパラメータフォーマットは、パッケージ名+:+リソースフォルダ名+/+リソース名です.このフォーマットでnullとすることができます
2>方式2
Resources resources = context.getResources(); 
int indentify= getResources().getIdentifier("icon", "drawable", "org.anddev.android.testproject");

1番目のパラメータはID名で、2番目はリソース属性がID["id"]またはDrawable["drawable"]で、3番目はパッケージ名です.
追加:
リソース内のその他のリソースを取得するには、次の手順に従います.
    1.stringを取得するには、次のように書くことができます.
    getResources().getIdentifier("name", "string", packdgeName);
    2.arrayの配列を取得するには、次のように書きます.
    getResources().getIdentifier("name", "array", packdgeName);