Question

I have a super simple class, it extends ImageView. I would like to add (in it's constructor) a parameter for an R.Drawable. ideally, I can then instantiate the custom Char class, and I would have a nice little ImageView with a background. I understand that this is fundamentally possible by just making an imageview and that I'm not customizing anything. This is more for learning though. How to I pass R.Drawable as a parameter? The code below states I can't assign a drawable to an int.

DOUBLE UPDATE: For a brief moment I saw an answer that said to just use int as a parameter. I thought of this, but that doesn't seem to be graceful at all. I figure Android probably has a more graceful way of approaching this. I tried looking through source doc but got lost in the maze. Apparently that IS the right answer though.

*imports*


public class Char extends ImageView {

    Char (Context context, R.drawable drawable){
        super(context);
        setBackgroundResource(drawable);
    }
}
Was it helpful?

Solution

public class Char extends ImageView {

    /**
     * Constructor for <code>Char</code>
     * 
     * @param context The {@link Context} to use
     * @param resId The resource identifier of the {@link Drawable}
     */
    public Char(Context context, int resId) {
        super(context);
        setImageResource(resId);
    }

}

To use it call: new Char(your_context, R.drawable.your_drawable))

OTHER TIPS

The answer you saw of passing an int is the correct one. Either that or you can create the drawable, pass it in and use that

public class Char extends ImageView {

    Char (Context context, Drawable drawable) {
        super(context);
        setBackgroundDrawable(drawable);
    }
}

R.drawable.xxx is an int, so just pass an int parameter to your function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top