简体   繁体   中英

how to get name of a drawable assets dynamically in android?

I have some photos in my drawable folder res that name of them is like

  • move1.jpg
  • move2.jpg
  • move3.jpg and so on.

I have a table in my database which has a field to store photo ID.

I have a selected list of items (in my case movement), that I want, user see the proper photo based on the Id of photo.

movements = db.getAllMovements(true);
...

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  Dialog movement_image_dialog = new Dialog(getActivity());
  movement_image_dialog.setContentView(R.layout.image_dialog);

  ImageView movement_imageView = (ImageView) movement_image_dialog.findViewById(R.id.movement_imageview);

  **int photoId = finalMovements.get(position).getPhotoId();**
  **movement_imageView.setImageResource(R.drawable.*move4*);**
...
}

My question is how I can set the Image resource with the photoId that I have? I need something like this R.drawalbe.(move+photoId)

You can use resource getIdentifier(String name, String defType, String defPackage) as

int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());

Where

this is an Activity.

nameOfDrawable is move1, move2 etc in your case.

drawableResourceId is the one you can pass in

movement_imageView.setImageResource(drawableResourceId);

we get dinamically images from like this.

String imageId=yourImageId;
    Drawable drawable = getResources().getDrawable(getResources()
                      .getIdentifier(imageId, "drawable", getPackageName()));

I think you should try this..

int photoId=R.drawable.move1;

img.setImageResource(photoId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM