2013-10-13 45 views
0

我有什么: 我有,我正在打印Bitmap image;point position;更新custome查看:Android的

@Override 
protected void onDraw(Canvas canvas) { 
    // TODO Auto-generated method stub 
    super.onDraw(canvas); 
    canvas.drawBitmap(carSpriteImage, carspritePosition.x , carspritePosition.y, null); 
}//end of OnDraw 

我想 我想通过更新位置CustomView类螺纹

public class AnimationHelperThread extends Thread{ 

CustomeView customeView; 

public AnimationHelperThread(CustomeView customeView){ 
    // TODO Auto-generated constructor stub 
    this.customeView=customeView; 
} 
@Override 
public void run() { 
    super.run(); 

    int x=0; 
    int y=0; 
    for(int i=0;i<1000;i++) 
    { 
     try { 
      Thread.sleep(400); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     Point p=new Point(); 
     p.set(x,y); 
     customeView.setCarspritePosition(p); 
     x+=1; 
     y+=2; 
     Log.i("Helper Thread", "Call "+i); 
    } 
} 

此方法不起作用请给我建议任何东西

+0

你有没有在设置好点对象后试过调用'customeView.invalidate();'? – gokhanakkurt

+0

是的,我试过了,但它给了异常“从错误的线程调用” –

+0

我无法通过查看上面的代码预测异常的原因。只有我可以说,你应该被要求更新'UI Thread'的视图有一个叫做'runOnUiThread(...)'的函数。尝试使用这个函数可能会有所帮助 – gokhanakkurt

回答

0

您只能从UIThread更改布局。尝试类似this.-

一个Context变量添加到您的自定义thread.-

Context context; 

public AnimationHelperThread(Context context, CustomeView customeView) { 
    // TODO Please, remove nasty autogenerated TODO comments 
    this.context = context; 
    this.customeView = customeView; 
} 

然后,假设你从Activity实例线程,你会do.-

AnimationHelperThread thread = new AnimationHelperThread(this, customView); 

最后,调用runOnUiThread通过context .-

context.runOnUiThread(new Runnable() { 
    public void run() { 
     Point p=new Point(); 
     p.set(x,y); 
     customeView.setCarspritePosition(p); 
    } 
}); 

请注意,您需要将xy定义为实例变量。

+0

我应该在AnimationHelper类中使用它吗? –

+0

不一定,但如果你这样做,应该没有问题。 – ssantos

+0

它不工作在线程扩展类 –