【发布时间】:2014-02-12 11:02:28
【问题描述】:
当我按下按钮 START 并结束它时,我想每 5 秒开始重复两行代码,当我按下按钮 STOP 时。我正在尝试使用 TimerTask 和 Handles,但无法弄清楚如何。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//final int i;
final TextView textView = (TextView) findViewById(R.id.textView);
final Button START_STOP = (Button) findViewById(R.id.START_STOP);
final ImageView random_note = (ImageView) findViewById(R.id.random_note);
final int min = 0;
final int max = 2;
final Integer[] image = { R.drawable.a0, R.drawable.a1,R.drawable.a2 };
START_STOP.setTag(1);
START_STOP.setText("START");
START_STOP.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int status = (Integer) v.getTag();
if (status ==1) {
textView.setText("Hello");
START_STOP.setText("STOP");
v.setTag(0);
final Random random = new Random();
//************************************************************
// I would like to loop next 2 lines of code every 5 seconds.//
int i = random.nextInt(2 - 0 + 1) + 0;
random_note.setImageResource(image[i]);
//************************************************************
}
else
{
textView.setText("Bye");
START_STOP.setText("Let's PLAY!");
v.setTag(1);
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
【问题讨论】:
-
TimerTask 有什么问题?
-
我不知道。当我试图在模拟器上运行它时,它崩溃了。但可能我做错了什么,因为我是 Android (Java) 初学者。
标签: android loops timer timertask handlers