当我创建一个使用View创建基本动画的应用程序时,使用无效的循环它会一次又一次地给出连续动画。但是,在使用SurfaceView时,使用invalidate会产生错误。有人能帮帮我吗?
package com.example.newapplication;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SurfaceAnimation extends SurfaceView implements Runnable{
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = true;
public SurfaceAnimation(Context context) {
super(context);
// TODO Auto-generated constructor stub
ourHolder = getHolder();
ourThread = new Thread(this);
ourThread.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(isRunning){
if(!ourHolder.getSurface().isValid())
continue;
else{
Canvas canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.CYAN);
ourHolder.unlockCanvasAndPost(canvas);
// invalidate();
}
}
}
}
上面的logcat是:
05-30 04:41:47.240: E/AndroidRuntime(1869): FATAL EXCEPTION: Thread-120
05-30 04:41:47.240: E/AndroidRuntime(1869): Process: com.example.newapplication, PID: 1869
05-30 04:41:47.240: E/AndroidRuntime(1869): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
05-30 04:41:47.240: E/AndroidRuntime(1869): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
05-30 04:41:47.240: E/AndroidRuntime(1869): at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:857)
05-30 04:41:47.240: E/AndroidRuntime(1869): at android.view.ViewGroup.invalidateChild(ViewGroup.java:4320)
05-30 04:41:47.240: E/AndroidRuntime(1869): at android.view.View.invalidate(View.java:10935)
05-30 04:41:47.240: E/AndroidRuntime(1869): at android.view.View.invalidate(View.java:10890)
05-30 04:41:47.240: E/AndroidRuntime(1869): at com.example.newapplication.SurfaceAnimation.run(SurfaceAnimation.java:35)
05-30 04:41:47.240: E/AndroidRuntime(1869): at java.lang.Thread.run(Thread.java:841)
答案 0 :(得分:1)
如果要从非ui线程更新视图,则必须使用postInvalidate()
而不是invalidate()
。这就是你的logcat所说的:
只有创建视图层次结构的原始线程才能触及它 视图。
答案 1 :(得分:1)
不要调用invalidate(),而是调用postInvalidate();