我正在测试创建游戏循环而不使用表面视图,但我无法让线程连续运行。在下面的代码中,我希望文本视图能够连续显示递减数字,但它只显示一次。
public class ActivityGameTest extends AppCompatActivity {
int bigNumber = Integer.MAX_VALUE;
Thread gameThread;
TextView myText;
private Handler uiHandler;
boolean mRun;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_test);
myText = (TextView) findViewById(R.id.txtHello);
uiHandler = new Handler();
gameThread = new Thread(null, processFrame, "ProcessFrame");
mRun = true;
gameThread.start();
}
private Runnable processFrame = new Runnable() {
@Override
public void run() {
while (mRun) {
updateFrame();
//编辑 - 添加这些行
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
private void updateFrame() {
bigNumber--;
uiHandler.post(showFrame);
}
private Runnable showFrame = new Runnable() {
@Override
public void run() {
myText.setText(Integer.toString(bigNumber));
}
};
}