因为设计游戏时,有一个需要每秒刷新50次的TextView.一开始用的是游戏线程调handler刷新UI的TextView,结果造成了线程阻塞.但是我又不想使用SurfaceView.查了两天,最后选用了以下办法:
1.继承TextView
2.在新的类内部刷新视图
以上代码参考Android自带的DigitalClock类,更详细的代码可以看DigitalClock.
1.继承TextView
2.在新的类内部刷新视图
代码:
package com.example.textsview;
import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.TextView;
public class TextSView extends TextView {
/** 时间步 */
public static final float TIME_STEP = 1f / 50f;
private Runnable mTicker;
private Handler mHandler;
private boolean mTickerStopped = false;
private int count = 1;
public TextSView(Context context) {
super(context);
}
public TextSView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onAttachedToWindow() {
mTickerStopped = false;
super.onAttachedToWindow();
mHandler = new Handler();
/**
* requests a tick on the next hard-second boundary
*/
mTicker = new Runnable() {
public void run() {
if (mTickerStopped) {
return;
}
setText("count:" + count++);
invalidate();
long next = SystemClock.uptimeMillis() + (long) (TIME_STEP * 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mTickerStopped = true;
}
}
以上代码参考Android自带的DigitalClock类,更详细的代码可以看DigitalClock.
最后感谢liarzn.