Handler通过接收Message 发送过来的常量值改变view状态,view调用的是invalidate()方法 触发了 onDraw()方法,在onDraw()方法里面设置了view的移动值。
下面是java 代码
package com.hander.com;
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 UI extends Activity {
protected static final int a= 1; //常量
Thread myRefreshThread = null;
YouXi myBounceView = null;
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case UI.a: //接收到常量值为1的消息
myBounceView.invalidate();
break;
}
// super.handleMessage(msg);
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.myBounceView = new YouXi(this);
this.setContentView(this.myBounceView); // 布局文件是view 对象
new Thread(new myThread()).start();
}
class myThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
Message message = new Message();
message.what = UI.a;
UI.this.myHandler.sendMessage(message); //发送 常量值为1的消息
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
view 代码
package com.hander.com;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.view.View;
public class YouXi extends View {
float x = 40;//这里是圆心位置,也是圆运动的起始位置
public YouXi(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
x+=10; //圆移动10个像素
Paint mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
canvas.drawCircle(x, 20, 20, mPaint);//画圆
}
}
阅读(761) | 评论(0) | 转发(0) |