[英]When my button is pressed, I get the error ViewRootImpl$CalledFromWrongThreadException
I tried to make a simple game on Android. 我试图在Android上制作一个简单的游戏。 The player is a blue ball and is supposed to avoid the moving objects.
玩家是一个蓝色的球,应该避免移动物体。 Once it hits it, the game is over.
一旦击中它,游戏就结束了。 The game also ends if the player catches all the food objects.
如果玩家抓到所有食物,游戏也会结束。 I got the collision detection working but when I tried to add a button afterwards to give the user the option to restart, I got the ViewRootImpl$CalledFromWrongThreadException error.
我使碰撞检测正常工作,但是当我以后尝试添加按钮以为用户提供重新启动选项时,出现了ViewRootImpl $ CalledFromWrongThreadException错误。 The button is already declared in the onCreate method and the visibility is set to invisible, but when I change it to visible, I get the error.
该按钮已经在onCreate方法中声明,并且可见性设置为不可见,但是当我将其更改为可见时,出现错误。 I have no idea how to fix it.
我不知道如何解决它。 I tried looking online and it wasn't much help.
我尝试在网上查找,并没有太大帮助。 I understood that the error occcurs when you modify the UI in a non-UI thread, but how would you fix that?
我了解在非UI线程中修改UI时会发生该错误,但是您将如何解决呢? Any help would be appreciated.
任何帮助,将不胜感激。 (:
(:
Here is the run method: 这是运行方法:
@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);
}
}
You can't touch views outside UI thread (and your SurfaceView
drawning happens on non-UI thread). 您无法在UI线程外触摸视图(并且
SurfaceView
绘制发生在非UI线程上)。 Just instead of doing this: 只是不这样做:
playAgain.setVisibility(View.VISIBLE);
do this: 做这个:
playAgain.post(new Runnable() {
@Override
public void run() {
playAgain.setVisibility(View.VISIBLE);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.