这是新的类代码:
package com.test.webservertest;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Timer;
/**
* Created by tester on 8/27/2015.
*/
public class TimerCounter extends Activity
{
TextView timerTextView;
long startTime = 0;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTextView = (TextView) findViewById(R.id.textView3);
Button b = (Button) findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}
@Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}
}
在onCreate的MainActivity.java文件中我做了:
private TimerCounter tc;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tc = new TimerCounter();
tc.onCreate(savedInstanceState);
}
现在运行程序时,我在TimerCounter类中遇到异常:
super.onCreate(savedInstanceState);
savedInstanceState null
我想要做的是使用TimerCounter类中的按钮,或者在运行程序时没有按钮,计时器将启动。
如何使用按钮而不使用按钮?
我在MainActivity设计器中添加了一个按钮和一个textView3
答案 0 :(得分:2)
onClick(View view)
中的代码并将其直接粘贴到onCreate(Bundle savedInstance)
。