自动秒表

时间:2018-12-16 01:35:56

标签: android

这是我的秒表应用程序代码。

public class MainActivity extends Activity {
    private int seconds=0;
    private boolean running;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(savedInstanceState !=null)
        {
            seconds=savedInstanceState.getInt("seconds");
            running=savedInstanceState.getBoolean("running");
        }
        runTimer();
    }

    public void onSaveInstanceState(Bundle savedInstanceState)
    {
        savedInstanceState.putInt("seconds", seconds);
        savedInstanceState.putBoolean("running", running);
    }
    public void onClickstart(View view)
    {
        running=true;
    }
    public void onClickstop(View view)
    {
        running=false;
    }
    public void onClickreset(View view)
    {
        running=false;
        seconds=0;
    }

    private void runTimer()
    {
        final TextView timeView=(TextView)findViewById(R.id.timeview);

        final Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                int hours= seconds/3600;
                int minutes= (seconds%3600)/60;
                int secs= seconds%60;

                String time= String.format("%02d:%02d:%02d",hours, minutes, secs);

                timeView.setText(time);

                if(running)
                {
                    seconds++;
                }
                handler.postDelayed(this, 1000);
            }
        });
    }
}

我还创建了按钮和背景。 我的问题是如何在应用启动时而不是使用“开始”按钮使计时器启动。我希望计时器在启动应用程序时自动启动,并且只有“停止并重置”按钮。

非常感谢您的帮助!

0 个答案:

没有答案