Java 通过线程扩展类更新custome视图:Android

Java 通过线程扩展类更新custome视图:Android,java,android,multithreading,bitmap,Java,Android,Multithreading,Bitmap,我所拥有的: 我有一个CustomView类,在这个类中我正在打印位图图像打开点位置 @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); canvas.drawBitmap(carSpriteImage, carspritePosition.x , carspritePosition.y, null); }//en

我所拥有的: 我有一个CustomView类,在这个类中我正在打印
位图图像打开<代码>点位置

@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);
    }
}
public类AnimationHelperThread扩展线程{
CustomeView CustomeView;
公共动画助手线程(CustomeView CustomeView){
//TODO自动生成的构造函数存根
this.customeView=customeView;
}
@凌驾
公开募捐{
super.run();
int x=0;
int y=0;

对于(int i=0;i您只能从
UIThread
更改布局。请尝试类似的方法-

上下文
变量添加到自定义线程-

Context context;

public AnimationHelperThread(Context context, CustomeView customeView) {
    // TODO Please, remove nasty autogenerated TODO comments
    this.context = context;
    this.customeView = customeView;
}
然后,假设您正在从
活动
实例化线程,您将执行以下操作-

AnimationHelperThread thread = new AnimationHelperThread(this, customView);
最后,通过
context
调用
runOnUiThread
-

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

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

在设置point对象后,您是否尝试调用
customeView.invalidate();
?是的,我尝试过,但出现异常“从错误线程调用”通过查看上面的代码,我无法预测异常的原因。我唯一能说的是,应该要求您更新
UI线程上的视图
有一个名为
runOnUiThread(…)
。尝试使用此函数可能会有帮助mm不一定,但如果您这样做,应该不会有问题。错误是runOnUiThread对于类型AnimationHelperThread是未定义的。对了,我的错,您需要将
上下文
传递到
AnimationHelperThread
实例。调用活动的实例就可以了。您能给我一个例子吗代码丰富,所以我能更好地理解…实际上我是动画新手,所以我需要一种方法来计算在其他线程和UI线程中的位置,只处理用户输入。当然,请在创建线程的地方发布相关代码,我猜你是从一个活动中做的,不是吗?