我想编写一个程序,通过SurfaceView在屏幕上移动球并更改drawCircle()方法的X参数,但程序不会在屏幕上显示任何内容,只显示黑页。
这是我的代码。
TestsSurface.java:
public class TestSurface extends SurfaceView implements SurfaceHolder.Callback{
SurfaceHolder surfaceHolder;
public TestSurface(Context context) {
super(context);
// TODO Auto-generated constructor stub
getHolder().addCallback(this);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
Thread thread=new Thread();
thread.start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void drawing(Canvas canvas){
drawingShape(canvas);
}
int x=100;
public void drawingShape(Canvas canvas){
canvas.drawColor(Color.BLACK);
Paint paint=new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(x, 100, 50, paint);
x+=2;
}
public void run(){
Canvas canvas;
while(true){
canvas=null;
try{
synchronized(surfaceHolder){
canvas=getHolder().lockCanvas();
drawing(canvas);
}
}finally{
if(canvas!=null)
getHolder().unlockCanvasAndPost(canvas);
}
}
}
}
MainActivity.java:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
TestSurface test=new TestSurface(this);
setContentView(test);
}
}
我的问题是什么?
答案 0 :(得分:0)
您的变量surfaceHolder
永远不会在调用synchronized()
考虑添加:
surfaceHolder = getHolder();
...给你的构造函数。
编辑以下评论::
Thread thread = new Thread(new Runnable() {
public void run() {
Canvas canvas;
while(true){
canvas=null;
try{
synchronized(surfaceHolder){
canvas=getHolder().lockCanvas();
drawing(canvas);
}
}finally{
if(canvas!=null)
getHolder().unlockCanvasAndPost(canvas);
}
Thread.Sleep(1000);
}
}
}).start();