如何为我创建的新类代码创建新实例?

时间:2015-08-27 02:02:23

标签: java android-studio

这是新的类代码:

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

1 个答案:

答案 0 :(得分:2)

  • 使用按钮启动和停止计时器:有一个很好的android example
  • 为了在没有按钮的情况下执行此操作,您可以剪切onClick(View view)中的代码并将其直接粘贴到onCreate(Bundle savedInstance)