我正试图在游戏结束时运行一个简单的按钮动画
我有以下课程:
GameView
GameThread
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
boolean gameover;GameThread gamethread;
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
gameover=true;
getHolder().addCallback(this); // adding the callback (this) to the surface holder to intercept events
setFocusable(true);// make the GamePanel focusable so it can handle events
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d("TAG", "surface changed");
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
gamethread=new GameThread(getHolder(),this);
gamethread.setrunning(true);
gamethread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry=true;
Log.d("TAG", "Surface destroyed entered");
while(retry){
try {
gamethread.setrunning(false);
gamethread.join();
gamethread=null;
Log.d("tag","thread is destroyed" );
if(gamethread==null){
Log.d("tag","thread is destroyed and null" );
}
retry=false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end while
}//end method
public void update(){
if(gameover){
Button gameover_button = (Button) findViewById(R.id.gameover);
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.gameoveranimation);
gameover_button.startAnimation(animation);
}
}//end update`
public class GameThread extends Thread {
// desired fps
private boolean running;
private SurfaceHolder surfaceholder;
private GameView gameview;
public GameThread(SurfaceHolder surfaceHolder, GameView gameview){
this.gameview=gameview;
this.surfaceholder=surfaceHolder; //we need the surfaceholder since we need to lock surface before drawing
}
public void setrunning(boolean running){
this.running=running;
}
@Override
public void run(){
super.run();
Canvas canvas;
while(running){
canvas=null;
canvas = this.surfaceholder.lockCanvas();
synchronized (surfaceholder) {
if(canvas!=null){
canvas.drawColor(Color.BLACK);
this.gameview.Draw1(canvas);
this.gameview.update();
}//end if
}
}
}finally{//in case of an exception
if(canvas!=null){
surfaceholder.unlockCanvasAndPost(canvas);
}
}//end finally
}//end loop
}//end run
}
<br>
除了gameview类的更新方法中的动画外,一切正常
动画在oncreate方法中运行正常
我知道我的问题与线程有关,但我对它们了解不多。
thx提前
`
答案 0 :(得分:1)
如果您的问题是需要在UI线程上调用update,那么您可以使用:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
this.gameview.update();
}
});
此外,看起来您正在寻找游戏结束按钮作为表面视图的孩子。如果这不正确,您可以找到相对于父活动的视图。
Activity activity = (Activity) getContext();
Button gameover_button = (Button) activity.findViewById(R.id.gameover);