尝试为我的表面视图添加简单的背景,但是drawBitmap似乎存在问题。我正在观看youtube教程,除了我制作了自己的可绘制xml布局文件(因为他没有显示他的内容)外,他所做的所有操作都一样,因此我认为问题可能出在simple.xml文件中。
错误
com.example.adam.hilo E/AndroidRuntime: FATAL EXCEPTION: Thread-2096
com.example.adam.hilo E/AndroidRuntime: Process: com.example.adam.hilo, PID: 19788
com.example.adam.hilo E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference
com.example.adam.hilo E/AndroidRuntime: at android.graphics.Canvas.throwIfCannotDraw(Canvas.java:1281)
com.example.adam.hilo E/AndroidRuntime: at android.graphics.Canvas.drawBitmap(Canvas.java:1337)
com.example.adam.hilo E/AndroidRuntime: at com.example.adam.hilo.Activity_Staircase_Layout.run(Activity_Staircase_Layout.java:36)
com.example.adam.hilo E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
Activity_Staircase_Layout
public class Activity_Staircase_Layout extends SurfaceView implements Runnable {
Thread thread = null;
boolean can_draw;
Bitmap background;
Canvas canvas;
SurfaceHolder surface_holder;
public Activity_Staircase_Layout(Context context) {
super(context);
surface_holder = getHolder();
background = BitmapFactory.decodeResource(getResources(), R.drawable.simple);
}
@Override
public void run() {
while(can_draw) {
if(!surface_holder.getSurface().isValid()) {
continue;
}
canvas = surface_holder.lockCanvas();
canvas.drawBitmap(background,0,0,null);
surface_holder.unlockCanvasAndPost(canvas);
}
}
public void pause() {
can_draw = false;
while(true) {
try {
thread.join();
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
thread = null;
}
public void resume() {
can_draw = true;
thread = new Thread(this);
thread.start();
}
}
drawable / Simple.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- Specify a semi-transparent solid green background color -->
<solid android:color="#5500FF66" />
<!-- Specify a dark green border -->
<stroke
android:width="5dp"
android:color="#009933" />
</shape>
StaircaseActivity.java
public class StaircaseActivity extends AppCompatActivity {
Activity_Staircase_Layout staircase_LayoutView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
staircase_LayoutView = new Activity_Staircase_Layout(this);
setContentView(staircase_LayoutView);
}
@Override
public void onPause() {
super.onPause();
staircase_LayoutView.pause();
}
@Override
public void onResume() {
super.onResume();
staircase_LayoutView.resume();
}
}
最佳答案
这里的问题是background
行中的位图为空:canvas.drawBitmap(background,0,0,null);
调用background
方法时,请确保drawBitmap
位图不为空。
请执行以下操作以确认这一点:
if(background != null){
canvas.drawBitmap(background,0,0,null);
} else {
Log.d("DEBUG","background is null");
}