计时器软件比较常见,很多手机会自带这个软件,就像计算器一样普遍。不过,这样的一个软件对我们来说依然还有很高的学习价值。
先来看看初始画面:
点击开始以后,定时器开始计时:
此时定时器会每秒变动一次,等一会儿以后点击暂停,定时器暂停定时:
点击重置以后,计时器恢复到0。重置不会修改定时器的运行状态,如果定时器原本是运行的,重置以后还会从0重新开始计时;如果定时器原本是暂停的,重置以后依旧还是暂停状态。
这样的一个软件是不是特别的简单呢?
实际上的却简单,不管用什么编程语言都异常容易实现。
昨天在做出了第一个安卓程序以后,我便连续做了大量的练习,看了很长时间的书,对于安卓的布局有了一定的认识。这个案例只是多个案例里面其中一个比较综合的案例。
在很多书或者视频教程中,这样的一个案例也通常会被作为综合案例出现。
我们先来看看整体的代码。
导入的依赖如下:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.SystemClock
import android.widget.Button
import android.widget.Chronometer
接着是初始化变量:
lateinit var stopWatch: Chronometer // 计时器
private var running = false // 是否正在运行
private var offset: Long = 0 // 计时偏移量
在onCreate方法中,我们获取按钮和定时器组件,设置按钮的回调方法:
// 获取计时器组件
stopWatch = findViewById(R.id.stopwatch)
// 获取开始按钮
val startButton = findViewById(R.id.start_button)
startButton.setOnClickListener {
if (!running) {
setBaseTime()
stopWatch.start() // 开始计时
running = true // 修改计时状态
}
}
// 获取暂停按钮
val stopButton = findViewById(R.id.stop_button)
stopButton.setOnClickListener {
if (running) {
saveOffset() // 保存偏移量
stopWatch.stop() // 停止计时
running = false
}
}
// 获取重置按钮
val resetButton = findViewById(R.id.reset_button)
resetButton.setOnClickListener {
offset = 0 // 重置偏移量
setBaseTime() // 设置基础时间
}
上面的代码中,用到了setBaseTime设置基础时间和saveOffset保存偏移量,这个两个方法的具体实现如下:
// 设置基础时间
private fun setBaseTime() {
stopWatch.base = SystemClock.elapsedRealtime() - offset
}
// 保存偏移量
private fun saveOffset() {
offset = SystemClock.elapsedRealtime() - stopWatch.base
}
接着我们看一下关于字符串的配置信息:strings.xml
再来看看整体的布局代码:activity_main.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
tools:context=".MainActivity">
android:id="@+id/stopwatch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="56sp"
tools:ignore="MissingConstraints" />
android:id="@+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/start"
tools:ignore="MissingConstraints" />
android:id="@+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/stop"
tools:ignore="MissingConstraints" />
android:id="@+id/reset_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/reset"
tools:ignore="MissingConstraints" />
我们使用了一个Chronometer定时器文本组件和三个Button按钮组件进行布局,并分别设置了id,方便我们后面根据id获取元素。
通过以上代码,我们就能够完成整个定时器综合案例的练习了。
这个案例最主要的还是学习价值,因为在真实的项目中,还是比较少见定时器这样的功能的。
经过一段时间的学习以后,我发现Android比Web更适合作为前端技术进行掌握。因为现在几乎人人都有安卓手机,安卓软件非常便于部署。最重要的是,我们可以不依赖服务器进行单机部署,非常的灵活。
当然,大鹏的主要精力还是会放在后端技术的深入研究上。安卓开发只是一个技术输出出口,它就像是一条奔流到海的河流一样,能够让大鹏的技术栈变得真正的活起来,而不再是自己一个人在很多技术积累当中自娱自乐。
领取专属 10元无门槛券
私享最新 技术干货