使用Android的线程实现View画图
过去习惯捣鼓JavaSE,画图什么的很轻松.结果到了Android画图的处理发生很大改变,这篇暂时研究View画图,后面再写一篇关于SurfaceView画图的
Android是单线程处理模型的,如果要并发线程无法更新主View,否则Android就会认为线程干扰错误,例如下面的代码就是错的:
new Thread( new Runnable() { public void run() { myView.invalidate(); } }).start();
下面代码的功能很简单:画一个圆出来,每隔0.1秒,圆向10移动10个像素。但可以清楚展示利用Handler更新UI的流程。
首先创建简单的View,代码如下:
package org.c30; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.view.View; public class BounceView extends View { float x = 40; public BounceView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { x+=10; Paint mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setColor(Color.GREEN); canvas.drawCircle(x, 40, 40, mPaint); } }
创建Activity,代码如下:
package org.c30; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.Window; public class TestHandler extends Activity { protected static final int UPMSG = 111; Thread myRefreshThread = null; BounceView myBounceView = null; Handler myHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case TestHandler.UPMSG : myBounceView.invalidate(); break; } super.handleMessage(msg); } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.myBounceView = new BounceView(this); this.setContentView(this.myBounceView); new Thread(new myThread()).start(); } class myThread implements Runnable { public void run() { while (!Thread.currentThread().isInterrupted()) { Message message = new Message(); message.what = TestHandler.UPMSG; TestHandler.this.myHandler.sendMessage(message); try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } }
分享到: | |
很好资料为什么只能看一会儿
?哪有一会
非常好的资料,
学习了,十分感谢。