[英]getting Error: non-static method 'getResources()' cannot be referenced from a static context
I'm working on an rpg game on Android studio using Java, and I have png pictures in the Drawable in Resource Manager.我正在使用 Java 在 Android Studio 上开发 rpg 游戏,并且我在资源管理器的 Drawable 中有 png 图片。 I'm trying to convert the drawable to bitmap, but I got the error.我正在尝试将 drawable 转换为位图,但出现错误。
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
public class Player implements GameObject{
private int direction;
private boolean move;
public Player(int direction, boolean move){//constructior
this.direction = direction;
this.move = move;
Drawable myDrawable = MainActivity.getResources().getDrawable(R.drawable.down_standing);
Bitmap downStanding = ((BitmapDrawable) myDrawable).getBitmap();
}
@Override
public void draw(Canvas canvas){
}
@Override
public void update(){
}
public void update(int direction, boolean move){
this.direction = direction;
this.move = move;
}
}
as for the MainActivity:至于 MainActivity:
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
Constants.SCREEN_WIDTH = dm.widthPixels;
Constants.SCREEN_HEIGHT = dm.heightPixels;
setContentView(new GamePanel(this));
}
}
Please help.请帮忙。 Thanks a lot!!非常感谢!!
To call getResources()
you'd have a Context
reference, you can't call it statically, so this is wrong:要调用getResources()
你有一个Context
引用,你不能静态调用它,所以这是错误的:
MainActivity.getResources()
To achieve it, you should provide a Context
parameter, which you can obtain from an Activity:要实现它,您应该提供一个Context
参数,您可以从 Activity 获取该参数:
public Player(int direction, boolean move, Context context){ //constructior with Context
this.direction = direction;
this.move = move;
Drawable myDrawable = context.getResources().getDrawable(R.drawable.down_standing); // This is right
Bitmap downStanding = ((BitmapDrawable) myDrawable).getBitmap();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.