📜  如何使用 Android Studio 创建秒表应用

📅  最后修改于: 2022-05-13 01:55:36.481000             🧑  作者: Mango

如何使用 Android Studio 创建秒表应用

在本文中,创建了一个 Android 应用程序来显示基本的秒表。

秒表的布局包括:

  • 一个 TextView :显示已经过去了多少时间
  • 三个按钮:
    1. 开始:启动秒表
    2. 停止:停止秒表
    3. 重置:将秒表重置为 00:00:00

创建秒表的步骤:

  • 为 Stopwatch App 创建一个新项目
  • 添加字符串资源
  • 更新秒表布局代码
  • 更新活动代码

以下是一一详细的步骤:

  1. 为 Stopwatch App 创建一个新项目
    • 为名为“Stopwatch”的应用程序创建一个新的 Android 项目,该应用程序的公司域为“geeksforgeeks.org”,将包名称设为 org.geeksforgeeks.stopwatch
      创建一个新项目并选择 Empty Activity

      创建一个新项目并选择 Empty Activity

      配置项目

      配置项目

    • 最低 SDK 应该是 API 14,因此它可以在几乎所有设备上运行。
    • 将创建一个名为“StopwatchActivity”的空活动和一个名为“activity_stopwatch”的布局。

      第一个开机画面

      第一个开机画面

  2. 添加字符串资源
    我们将在秒表布局中使用三个字符串值,一个用于每个按钮的文本值。这些值是字符串资源,因此需要将它们添加到字符串.xml中。将以下字符串值添加到您的字符串.xml版本中:
    Strings.xml
    
        GFG|Stopwatch
        Start
        Stop
        Reset
    


    activity_stopwatch.xml
    
    
        android:background="#0F9D58"
        android:padding="16dp"
        tools:context="org.geeksforgeeks.stopwatch.StopwatchActivity">
      
        
            
            android:id="@+id/time_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
      
            
            
            android:textAppearance="@android:style/TextAppearance.Large"
            android:textSize="56sp" />
      
        


    StopwatchActivity.java
    package org.geeksforgeeks.stopwatch;
      
    import android.app.Activity;
    import android.os.Handler;
    import android.view.View;
    import android.os.Bundle;
    import java.util.Locale;
    import android.widget.TextView;
      
    public class StopwatchActivity extends Activity {
      
        // Use seconds, running and wasRunning respectively
        // to record the number of seconds passed,
        // whether the stopwatch is running and
        // whether the stopwatch was running
        // before the activity was paused.
      
        // Number of seconds displayed
        // on the stopwatch.
        private int seconds = 0;
      
        // Is the stopwatch running?
        private boolean running;
      
        private boolean wasRunning;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_stopwatch);
            if (savedInstanceState != null) {
      
                // Get the previous state of the stopwatch
                // if the activity has been
                // destroyed and recreated.
                seconds
                    = savedInstanceState
                          .getInt("seconds");
                running
                    = savedInstanceState
                          .getBoolean("running");
                wasRunning
                    = savedInstanceState
                          .getBoolean("wasRunning");
            }
            runTimer();
        }
      
        // Save the state of the stopwatch
        // if it's about to be destroyed.
        @Override
        public void onSaveInstanceState(
            Bundle savedInstanceState)
        {
            savedInstanceState
                .putInt("seconds", seconds);
            savedInstanceState
                .putBoolean("running", running);
            savedInstanceState
                .putBoolean("wasRunning", wasRunning);
        }
      
        // If the activity is paused,
        // stop the stopwatch.
        @Override
        protected void onPause()
        {
            super.onPause();
            wasRunning = running;
            running = false;
        }
      
        // If the activity is resumed,
        // start the stopwatch
        // again if it was running previously.
        @Override
        protected void onResume()
        {
            super.onResume();
            if (wasRunning) {
                running = true;
            }
        }
      
        // Start the stopwatch running
        // when the Start button is clicked.
        // Below method gets called
        // when the Start button is clicked.
        public void onClickStart(View view)
        {
            running = true;
        }
      
        // Stop the stopwatch running
        // when the Stop button is clicked.
        // Below method gets called
        // when the Stop button is clicked.
        public void onClickStop(View view)
        {
            running = false;
        }
      
        // Reset the stopwatch when
        // the Reset button is clicked.
        // Below method gets called
        // when the Reset button is clicked.
        public void onClickReset(View view)
        {
            running = false;
            seconds = 0;
        }
      
        // Sets the NUmber of seconds on the timer.
        // The runTimer() method uses a Handler
        // to increment the seconds and
        // update the text view.
        private void runTimer()
        {
      
            // Get the text view.
            final TextView timeView
                = (TextView)findViewById(
                    R.id.time_view);
      
            // Creates a new Handler
            final Handler handler
                = new Handler();
      
            // Call the post() method,
            // passing in a new Runnable.
            // The post() method processes
            // code without a delay,
            // so the code in the Runnable
            // will run almost immediately.
            handler.post(new Runnable() {
                @Override
      
                public void run()
                {
                    int hours = seconds / 3600;
                    int minutes = (seconds % 3600) / 60;
                    int secs = seconds % 60;
      
                    // Format the seconds into hours, minutes,
                    // and seconds.
                    String time
                        = String
                              .format(Locale.getDefault(),
                                      "%d:%02d:%02d", hours,
                                      minutes, secs);
      
                    // Set the text view text.
                    timeView.setText(time);
      
                    // If running is true, increment the
                    // seconds variable.
                    if (running) {
                        seconds++;
                    }
      
                    // Post the code again
                    // with a delay of 1 second.
                    handler.postDelayed(this, 1000);
                }
            });
        }
    }


  3. 更新秒表布局代码
    这是布局的 XML。它描述了用于显示计时器的单个文本视图,以及用于控制秒表的三个按钮。将activity_stopwatch.xml中当前的 XML 替换为此处显示的 XML:

    activity_stopwatch.xml

    
    
        android:background="#0F9D58"
        android:padding="16dp"
        tools:context="org.geeksforgeeks.stopwatch.StopwatchActivity">
      
        
            
            android:id="@+id/time_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
      
            
            
            android:textAppearance="@android:style/TextAppearance.Large"
            android:textSize="56sp" />
      
        
  4. 活动代码将如何工作
    布局定义了三个按钮,我们将使用它们来控制秒表。每个按钮都使用其 onClick 属性来指定单击按钮时应运行 Activity 中的哪个方法。单击 Start 按钮时,将调用onClickStart() 方法,单击 Stop 按钮时将调用onClickStop() 方法,单击 Reset 按钮时将调用onClickReset() 方法。我们将使用这些方法来启动、停止和重置秒表。

    我们将使用我们将创建的名为runTimer()的方法更新秒表。 runTimer()方法将每秒运行一次代码以检查秒表是否正在运行,如果是,则增加秒数并在文本视图中显示秒数。

    为了帮助我们解决这个问题,我们将使用两个私有变量来记录秒表的状态。我们将使用一个名为seconds整数来跟踪自秒表开始运行以来已经过去了多少秒,并使用一个名为running布尔值来记录秒表当前是否正在运行。

    我们将从编写按钮的代码开始,然后我们将查看runTimer()方法。

    • 为按钮添加代码当用户单击“开始”按钮时,我们将运行变量设置为true ,以便秒表启动。当用户点击 Stop 按钮时,我们将running设置为false ,以便秒表停止运行。如果用户点击 Reset 按钮,我们会将running设置为false并将seconds设置为0 ,以便秒表重置并停止运行。
    • runTimer() 方法接下来我们需要做的是创建runTimer()方法。该方法将获取布局中文本视图的引用;将seconds变量的内容格式化为小时、分钟和秒;然后在文本视图中显示结果。如果running变量设置为true ,它将增加seconds变量。
    • 处理程序允许您安排代码处理程序是一个 Android 类,您可以使用它来安排应该在未来某个时间运行的代码。您还可以使用它来发布需要在不同于主 Android 线程的线程上运行的代码。在我们的例子中,我们将使用Handler来安排秒表代码每秒运行一次。
      要使用Handler ,您将希望调度的代码包装在Runnable对象中,然后使用Handle post()postDelayed()方法指定您希望代码运行的时间。
    • post() 方法post()方法发布需要尽快运行的代码(通常是立即运行)。此方法采用一个参数,即Runnable类型的对象。 Androidville 中的Runnable对象就像普通Java中的Runnable一样:您想要运行的作业。你把要运行的代码放在Runnable的run()方法中, Handler会确保代码尽快运行。
    • postDelayed() 方法postDelayed()方法的工作方式与post()方法类似,只是您使用它来发布应该在将来运行的代码。 postDelayed()方法有两个参数:一个Runnable和一个longRunnable包含您要在其run()方法中运行的代码, long指定您希望将代码延迟的毫秒数。代码将在延迟后尽快运行。

    下面是StopwatchActivity 的以下代码。Java

    秒表活动。Java

    package org.geeksforgeeks.stopwatch;
      
    import android.app.Activity;
    import android.os.Handler;
    import android.view.View;
    import android.os.Bundle;
    import java.util.Locale;
    import android.widget.TextView;
      
    public class StopwatchActivity extends Activity {
      
        // Use seconds, running and wasRunning respectively
        // to record the number of seconds passed,
        // whether the stopwatch is running and
        // whether the stopwatch was running
        // before the activity was paused.
      
        // Number of seconds displayed
        // on the stopwatch.
        private int seconds = 0;
      
        // Is the stopwatch running?
        private boolean running;
      
        private boolean wasRunning;
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_stopwatch);
            if (savedInstanceState != null) {
      
                // Get the previous state of the stopwatch
                // if the activity has been
                // destroyed and recreated.
                seconds
                    = savedInstanceState
                          .getInt("seconds");
                running
                    = savedInstanceState
                          .getBoolean("running");
                wasRunning
                    = savedInstanceState
                          .getBoolean("wasRunning");
            }
            runTimer();
        }
      
        // Save the state of the stopwatch
        // if it's about to be destroyed.
        @Override
        public void onSaveInstanceState(
            Bundle savedInstanceState)
        {
            savedInstanceState
                .putInt("seconds", seconds);
            savedInstanceState
                .putBoolean("running", running);
            savedInstanceState
                .putBoolean("wasRunning", wasRunning);
        }
      
        // If the activity is paused,
        // stop the stopwatch.
        @Override
        protected void onPause()
        {
            super.onPause();
            wasRunning = running;
            running = false;
        }
      
        // If the activity is resumed,
        // start the stopwatch
        // again if it was running previously.
        @Override
        protected void onResume()
        {
            super.onResume();
            if (wasRunning) {
                running = true;
            }
        }
      
        // Start the stopwatch running
        // when the Start button is clicked.
        // Below method gets called
        // when the Start button is clicked.
        public void onClickStart(View view)
        {
            running = true;
        }
      
        // Stop the stopwatch running
        // when the Stop button is clicked.
        // Below method gets called
        // when the Stop button is clicked.
        public void onClickStop(View view)
        {
            running = false;
        }
      
        // Reset the stopwatch when
        // the Reset button is clicked.
        // Below method gets called
        // when the Reset button is clicked.
        public void onClickReset(View view)
        {
            running = false;
            seconds = 0;
        }
      
        // Sets the NUmber of seconds on the timer.
        // The runTimer() method uses a Handler
        // to increment the seconds and
        // update the text view.
        private void runTimer()
        {
      
            // Get the text view.
            final TextView timeView
                = (TextView)findViewById(
                    R.id.time_view);
      
            // Creates a new Handler
            final Handler handler
                = new Handler();
      
            // Call the post() method,
            // passing in a new Runnable.
            // The post() method processes
            // code without a delay,
            // so the code in the Runnable
            // will run almost immediately.
            handler.post(new Runnable() {
                @Override
      
                public void run()
                {
                    int hours = seconds / 3600;
                    int minutes = (seconds % 3600) / 60;
                    int secs = seconds % 60;
      
                    // Format the seconds into hours, minutes,
                    // and seconds.
                    String time
                        = String
                              .format(Locale.getDefault(),
                                      "%d:%02d:%02d", hours,
                                      minutes, secs);
      
                    // Set the text view text.
                    timeView.setText(time);
      
                    // If running is true, increment the
                    // seconds variable.
                    if (running) {
                        seconds++;
                    }
      
                    // Post the code again
                    // with a delay of 1 second.
                    handler.postDelayed(this, 1000);
                }
            });
        }
    }
    

输出:

秒表应用程序的输出。

秒表应用程序的输出。