更新游戏画面时线程的问题

作者daytodayme
http://www.iteye.com/topic/435147
[b]
调用Handler.post(Runnable r)方法,Runnable运行在UI所在线程,所以可以直接调用View.invalidate()[/b]

[quote]package com.ray.test;

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.view.View;

public class TestHandler extends Activity {
private MyView myView;
private Handler mHandler;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = new MyView(this);
mHandler = new Handler();
mHandler.post(new Runnable(){
@Override
public void run() {
myView.invalidate();
mHandler.postDelayed(this, 5);
}
});
setContentView(myView);
}

class MyView extends View{
private float x = 0f;
public MyView(Context context) {
super(context);

}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
x+=1;
Paint mPaint = new Paint();
mPaint.setColor(Color.BLUE);
canvas.drawRect(x, 40, x+40, 80, mPaint);
}

}
} [/quote]

[b]
在新线程里更新UI,可以直接postInvalidate() [/b]

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);

myView = new MyView(this);
this.setContentView(this.myView);
new Thread(new myThread()).start();
}

class myThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
myView.postInvalidate();
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值