我是Android的新手,我想做一个简单的例子,我点击一个开始按钮,另一个Activity打开,有一个简单的数字从一个开始向上计数,但我面临一个问题,之后我在onCreate方法上初始化了一些变量(在第二个活动中),我应该在哪里实际启动while语句来计算和修改文本视图?
我写了这堂课:
public class Counter extends Thread{
private TextView tv;
private int i;
public Counter( TextView tv ){
this.tv = tv;
}
@Override
public void run() {
while( true ){
tv.setText(i);
try {
sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
}
在这里开始了这个主题:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
counter = new Counter( (TextView) findViewById(R.id.textView2) );
counter.start( );
}
答案 0 :(得分:0)
@SuppressLint("UseValueOf")
final Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
// change your text here
if (condition) {
i++;
txt_TimeRecord.setText("" + i);
} else {
i = 0;
}
handler.postDelayed(this, 1 * 1000L);
}
});
[正确格式化代码]
答案 1 :(得分:0)
//In first activity
//set onclick method to that button.
public void onclick(view v)
{
Intent intent = new Intent(this, secondactivity.class);
startActivity(intent);
}
// in second activity in
// initi i value.
while(i<10)
{
i++ ;
// sleep statement
//print that i in textview
}
答案 2 :(得分:0)
我从类似的帖子中找到了我需要的东西,因为只有UI线程可以更新用户界面所以需要处理程序。
private void countNumbers() {
final TextView numbers = (TextView) findViewById(R.id.textView2);
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
int i = 0;
while (i++ < 500) {
try {
Thread.sleep(10);
}
catch (InterruptedException e) {
e.printStackTrace();
}
final int j = i;
handler.post(new Runnable(){
public void run() {
numbers.setText(Integer.toString(j));
}
});
}
}
};
new Thread(runnable).start();
}
方法countNumbers()在onCreate()中调用。