Question

I basically made a class, with this method:

    void setResource(Context context, R.id resourceID) {
    ImageView test = (ImageView) context.findViewById(resourceID);
    }

The "findViewById" gives me a can't resolve method. I have three ImageViews defined in XML, I would like to set the image associated to them programatically. in my main_activty I do so by using:

    ImageView blah = (ImageView) this.findViewById(R.id.blah);

Then:

    blah.setImageResource(R.drawable.pony);

HOWEVER, I would like to pass everything to my class I made and have it handle all that in the custom class, but when I try to pass everything (the code at the very top; "setResource") I get that findViewByID can't resolve method. Is there a way to do it that way?

Was it helpful?

Solution

I think you are trying to find the words to express what you are trying to do, and with some of the basic concepts. This is my best guess of what you are trying to accomplish...

The code below takes an id for drawable, loads it, and then puts it into an imageView in your layout. The ImageView must already be there in your layout, it does not create one for you dynamically.

void setResource(Context context, int resourceId) {

    //resourceId = R.drawable.ponies (example)
    Drawable drawable = context.getResources().getDrawable(resourceId);

    //R.id.main_imageview is example imageView in a layout.
    ImageView iv = findViewById(R.id.main_imageview);
    iv.setImageDrawable(drawable);
}   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top