android中View的实时刷新

    技术2022-05-19  47

    昨天在做一个界面时,想在用户touch屏幕之后先绘图一下,待逻辑处理完毕,再绘制最后的图,查看View的重绘方法,得知是invalidate()函数,于是在代码中这么写道:

     

    view plain copy to clipboard print ? public class PuzzleView extends View {      @Override      protected void onDraw(Canvas canvas) {       ...      }        @Override      public boolean onTouchEvent(MotionEvent event) {        invalidate();        //处理逻辑        invalidate();     }  }  

     

      写完,运行,oh,my god,只有第二次invalidate做了,第一次打酱油去了,翻资料,翻啊翻,看到Invalidate()的描述是这样的:当调用线程处于空闲状态时,会调用onDraw,刷新界面,也就是说,该函数仅是标记当前界面过期,并不直接负责刷新界面,奶奶的,不刷。。。继续翻啊翻,看到SurfaceView 能实现实时刷新,代码结构如下:

     

    view plain copy to clipboard print ? 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);            }          }       }   }  

     

    好了,这样写好后,只要在以前调用invalidate()的地方调用repaint()就OK了~


    最新回复(0)