通过Thread扩展类更新自定义View:Android

时间:2013-10-13 13:03:07

标签: java android multithreading bitmap

我有什么: 我有CustomView类,我在Bitmap image;

上打印point position;
@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

我想要 我想通过线程更新位置

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);
    }
}

这种方法不起作用请建议我任何事情

1 个答案:

答案 0 :(得分:0)

您只能更改UIThread的布局。尝试这样的事情.-

Context变量添加到自定义主题.-

Context context;

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

然后,假设你要从Activity实例化线程,你就可以了.-

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定义为实例变量。