开发者

How to get to resource 'R.raw.img' + r in java?

I have image resources img1,img2,...img10,how to reference them dynamically in the code below?

    for (int r=1; r<=10; r++){
        TableRow tr = new TableRow(this);
        ImageView im = new ImageView (this);
        im.setImageDrawable(getResources().getDrawable(R.raw.img1));
     ...

What I want to do is开发者_C百科 to get reference to 'R.raw.img' + r...


This is not merely possible in the way you said.
Here is a solution:
You need a typed array in the resources and use it like described on this site from Google.
In short, create your resource file like this,

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="pictures">
        <item>@drawable/img1</item>
        <item>@drawable/img2</item>
        <item>@drawable/img3</item>
    </array>
</resources>

Code this way,

Resources res = getResources();
TypedArray pics = res.obtainTypedArray(R.array.pictures);

You can then iterate through the array like this,

for (i.....)
    Drawable drawable = pics.getDrawable(i);


Probably easiest is to do:

int[] images = new int[]{
    R.raw.img1, R.raw.img2 .... 
};
for (int r=1; r<=10; r++){
    TableRow tr = new TableRow(this);
    ImageView im = new ImageView (this);
    im.setImageDrawable(getResources().getDrawable(images[i]));
 ...

If you wanna get rid of the array, you need reflection


Try this:

Bitmap _scratch = BitmapFactory.decodeResource(getResources(), R.drawable.img1);

You will need to import Bitmap and BitmapFactory. _scratch is a working handle to the resource R.drawable.img1

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜