0

アンドロイドはまだ初心者です。穏やかな。ImageView を動的に設定することに関する多くの記事を読みました。特定の方法で行う必要がありますが、正しい構文に苦労しています。皮肉なことに、私は iOS でこれを行う方法を知っていますが、Android では完全に困惑しています。以下はコードです。

画像リソースの名前とその場所を動的に入力したいと思います。

//Set the string to lower case
String animalImageLocation = animalName.toLowerCase()+"icon";
//Prepare to set the value of the ImageView
animalView = (ImageView)findViewById(R.id.animalView);
//Dynamically populate the image into the animalView
animalView.setImageResource(getResources().getIdentifier("R.Drawable."+<dynamicValue??>,null,null));

私はこれを試しましたが失敗しました。

//Set the string to lower case
    String animalImageLocation = animalName.toLowerCase()+"icon";
    //Prepare to set the value of the ImageView
    animalView = (ImageView)findViewById(R.id.animalView);
    //Dynamically populate the image into the animalView
    animalView.setImageResource(getResources().getIdentifier("R.Drawable."+animalImageLocation,null,null));

私はいくつかの方法を試しましたが、そのすべてが画像を表示しないか、単にクラッシュしました。getIdentifier() に効果的に画像名、つまり R.Drawable.bearicon を入力する必要があります

何か案は?

ジェレミー

4

1 に答える 1

1

まず、R.drawable資本がありません。これは重要だと思います。nullまた、クラスとして渡す場合は、それも提供する必要があります。

代わりに次のことを試してください。

animalView.setImageResource(
    getResources().getIdentifier(
        animalImageLocation,
        "drawable",
        animalView.getContext().getPackageName()
    )
);

nullまたは、後者の引数を渡すことを好む場合は、おそらく次のようになります。

animalView.setImageResource(
    getResources().getIdentifier(
        animalView.getContext().getPackageName() + ":drawable/" + animalImageLocation,
        null,
        null
    )
);
于 2013-04-06T03:54:13.340 に答える