我试图在Android上制作一款简单的游戏。玩家是一个蓝色的球,应该避免移动的物体。一旦它击中它,游戏就结束了。如果玩家捕获所有食物对象,游戏也会结束。我得到了碰撞检测功能,但是当我尝试添加一个按钮以便用户重新启动时,我得到了ViewRootImpl $ CalledFromWrongThreadException错误。该按钮已在onCreate方法中声明,并且可见性设置为不可见,但当我将其更改为可见时,我收到错误。我不知道如何解决它。我尝试在网上寻找并没有多大帮助。我知道在非UI线程中修改UI时会出现错误,但是如何解决?任何帮助,将不胜感激。 (:
这是run方法:
@Override
public void run() {
// TODO Auto-generated method stub
while(locker==true){
//checks if the lockCanvas() method will be success,and if not, will check this statement again
if(!holder.getSurface().isValid()){
continue;
}
/** Start editing pixels in this surface.*/
Canvas canvas = holder.lockCanvas();
draw(canvas);
if (up==true){
y=y-3;
}
else if(down==true){
y=y+3;
}
else if (left==true){
x=x-3;
}
else if (right==true){
x=x+3;
}
int counter=0;
for(int i=0;i<listOfFs.length;i++)
{
foodCaught [i] = listOfFs [i].check (x,y,radiusBlack);
if (foodCaught [i] == true)
{
alive [i] = listOfFs [i].kill ();
}
else{
counter++;
}
}
if (counter==0){
win=true;
playAgain.setVisibility(View.VISIBLE);
}
for(int i=0;i<listOfCs.length;i++)
{
if (i<3){
listOfCs[i].changeX(listOfCs[i].getX()+increment[i]);
}
else{
listOfCs[i].changeY(listOfCs[i].getY()+increment[i]);
}
}
for(int i=0;i<listOfCs.length;i++){
if (y+radiusBlack>listOfCs[i].getY()&& y-radiusBlack<listOfCs[i].getY()+listOfCs[i].getSize()&& x-radiusBlack<listOfCs[i].getX()+listOfCs[i].getSize()&& x+radiusBlack>listOfCs[i].getX())
{
chaserCaught = true;
playAgain.setVisibility(View.VISIBLE);
}
}
// End of painting to canvas. system will paint with this canvas,to the surface.
holder.unlockCanvasAndPost(canvas);
}
}
答案 0 :(得分:0)
您无法触摸UI线程之外的视图(并且您的SurfaceView
绘制发生在非UI线程上)。
而不是这样做:
playAgain.setVisibility(View.VISIBLE);
这样做:
playAgain.post(new Runnable() {
@Override
public void run() {
playAgain.setVisibility(View.VISIBLE);
}
});