user2061352
user2061352

Reputation: 29

how to load images from resources

How can I load images from resource folder in my GridView Adapter ?

I have a 200 images in resource folder i named them as name_1.png,name_2.png.

I want to load image and text view into android gridview element and show the images according to the number from resource folder.

I am able to show the text view data but not the images.

can any one suggest me how to do this. I am thinking that I have to write code in getview method to change the image.

This is getview method that I tried

Upvotes: 0

Views: 5490

Answers (2)

albaspazio
albaspazio

Reputation: 181

just a convenient refactoring of the accepted answer if you use kotlin and like using its extensions functions:

fun ImageView.loadDrawableFromName(name:String, ctx: Context, visible:Int=View.VISIBLE){
    val resId = ctx.resources.getIdentifier(name, "drawable", ctx.packageName)
    this.setImageResource(resId)
    this.visibility = visible
}

you can call it in both ways:

imgname="IMGNAME"
myimageview.loadDrawableFromName(imgname, ctx)

and

imgname="IMGNAME"
myimageview.loadDrawableFromName("@drawable/$imgname", ctx)

Upvotes: 0

Nathua
Nathua

Reputation: 8826

Put your images into drawable folder and reach them by name, then you access them by name.

int resourceId = context.getResources().getIdentifier(name, "drawable", 
      context.getPackageName());

Then you can use the resource

 imageView.setImageResource(resourceId);

or

 imageView.setBackgroundResource(resourceId);

Upvotes: 5

Related Questions