如何将 Drawable 传递给 class?

How to pass a Drawable into a class?

有没有像这样通过 class 传递 Drawable 的方法:

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;
}

正在尝试将 Drawable 传递到 class:

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

它说 getResources().getDrawable(drawable); 已弃用。那么我怎样才能像这样通过 class 传递 Drawable

首先,将int drawable参数更改为Drawable drawable

getResources().getDrawable(drawable); 起已弃用,您需要将其替换为 ContextCompat.getDrawable(context, R.drawable.my_drawable)

Context context开始参数是多余的,您可以删除它:

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;
}

然后,尝试将其传递到 class:

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