How to pass a Drawable into a class?

Is there anyway to pass a Drawable through a class like so:

public loadImage(Context context, int drawable, int x, int y, int width, int height) {
    this.drawable = context.getResources().getDrawable(drawable);
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
}

Trying to pass the Drawable into the class:

candyImg = new loadImage(getContext(), getResources().getDrawable(R.drawable.candy), 0, 0, 50, 50);

It says getResources().getDrawable(drawable); is deprecated. So how can I pass a Drawable through a class like so.

Upvotes: 2

Views: 834

Answers (1)

Anggrayudi H
Anggrayudi H

Reputation: 15155

First, change int drawable parameter to Drawable drawable.

As of getResources().getDrawable(drawable); is deprecated, you need to replace it with ContextCompat.getDrawable(context, R.drawable.my_drawable).

As of Context context parameter is redundant, you can remove it:

public loadImage(Drawable drawable, int x, int y, int width, int height) {
    this.drawable = drawable;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}

Then, try to pass it into the class:

candyImg = new loadImage(ContextCompat.getDrawable(this, R.drawable.my_drawable), 0, 0, 50, 50);

Upvotes: 1

Related Questions