该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
Android中View的实时刷新
Android中在做一个界面时,想在用户触摸屏幕之后先绘图一下,待逻辑处理完毕,再绘制最后的图,查看View的重绘方法,得知是invalidate()函数,于是在代码中这么写道:
public class PuzzleView extends View {
@Override
protected void onDraw(Canvas canvas) {
//...
}
@Override
public
boolean onTouchEvent(MotionEvent event)
{
invalidate();
//处理逻辑
invalidate();
}
}
运行后发现只有第二次invalidate做了,第一次打酱油去了,于是查找资料,看到Invalidate()的描述是这样的:当调用线程处于空闲状态时,会调用onDraw,刷新界面,也就是说,该函数仅是标记当前界面过期,并不直接负责刷新界面,继续翻啊翻,看到
SurfaceView能实现实时刷新,代码结构如下:
public class PuzzleView extends SurfaceView implements SurfaceHolder.Callback{
private
SurfaceHolder
surfaceHolder;
public
PuzzleView(Context
context){
//....
surfaceHolder =
this.getHolder();//获取holder
surfaceHolder.addCallback(this);
}
protected void paint(Canvas canvas) {
//这里的代码跟继承View时OnDraw中一样
}
public
void repaint() {
Canvas c =
null;
try
{
c =
surfaceHolder.lockCanvas();
paint(c);
}
finally {
if (c
!= null)
{
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}