最近要做这么一个东西,在一个activity中,实现多个计时器,点击哪个按钮,就开启哪个计时器。如下图:
涉及线程操作、更新ui。看着好简单,做起来还真花我不少功夫,主要是没理清这个思路,所以写代码的时候,先设计好真的很重要!!!写在博客里,让困惑的同学少走弯路吧,也给我提个醒,写代码先设计,想想行的通不。
主要是这么一个问题:每点Button的时候,就开启一个线程进行倒计时这种耗时操作(这思路其实有问题),再点其他倒计时按钮的时候就出问题了,每多点一次,倒计时速度就加快了。在这个问题困扰很久。。。因为点击倒计时按钮,主开启一个子线程,再点击倒计时按钮,就会在子线程中开启一个子线程,从而倒计时速度加快,明白了这个,实现这个功能就不是啥问题了。
最终的解决思路是,只开启一次子线程,每次点击按钮的时候,我只改变倒计时的时间就好了。当然把这个时间设置成全局的。
我绕了路,通过service实现了,其实一个activity就够了。
贴出代码:
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myself.timer2.MainActivity">
<LinearLayout
android:id="@+id/ll_clock"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#737373">
<TextView
android:id="@+id/tv_clock"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="00:00"
android:textColor="#ffffff"
android:textSize="80dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/ll_layout1"
android:layout_below="@+id/ll_clock"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:onClick="onClick"
android:id="@+id/btn_03"
android:layout_weight="1"
android:text="3分钟"
android:layout_width=