我使用兩個NumberPickers創建了一個簡單的應用程序,用於選擇一定數量的分鐘和秒鐘。沒有太多的代碼,所以我將它張貼在這裏:應用程序在開始之前崩潰
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "Interval Trainer";
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startButton;
public TextView text;
private final long interval = 1 * 1000;
//Create NumberPickers
NumberPicker numberPicker1 = (NumberPicker) findViewById(R.id.numberPicker1);
NumberPicker numberPicker2 = (NumberPicker) findViewById(R.id.numberPicker2);
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG,"Entering onCreate()");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button) this.findViewById(R.id.button);
startButton.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
//Set min and max values for NumberPickers
numberPicker1.setMaxValue(100);
numberPicker1.setMinValue(0);
numberPicker2.setMaxValue(59); //This is the seconds picker
numberPicker2.setMinValue(0);
Log.i(TAG,"Exiting onCreate()");
}
@Override
public void onClick(View v) {
//Calculate total time from NumberPickers in seconds
long startTime = (numberPicker1.getValue() * 60) + numberPicker2.getValue();
//Create CountDownTimer with values from NumberPickers
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime/1000)); //should be removed
if(!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startButton.setText("STOP");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startButton.setText("RESTART");
}
//Disable the NumberPickers after 'Start' is pressed
numberPicker1.setEnabled(false);
numberPicker2.setEnabled(false);
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
@Override
public void onFinish() {
text.setText("Time's up!");
//re-enable the NumberPickers once countdown is done
numberPicker1.setEnabled(true);
numberPicker2.setEnabled(true);
}
@Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished/1000);
//Changes the value of the NumberPickers after each tick
}
}
}
我有一種感覺崩潰有關,我宣佈的任何方法外兩個NumberPickers(這會自動將它們靜態?)。最初我在我的onCreate()中有這兩行代碼,但因爲我需要他們在我的內部類和其他方法我把它移到外面。這是什麼導致了崩潰?如果是這樣,我該如何正確執行此操作,並仍然可以訪問我的課程(包括內部課程)周圍的numberPicker1和2?
謝謝!
另外,如果你仔細閱讀你的代碼,你會看到'TextView的text'已經這樣做了:) – Fllo