Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 秒殺倒計時:自訂 TimeTextView

編輯:關於 Android 程式設計

電商類 App 的限時特賣幾乎都會用到倒計時。與其每次都在 Activity 裡寫計時器,不如封裝成一個自訂 View。以下這個 TimeTextView 繼承自 TextView,實作 Runnable,用 postDelayed 每秒刷新一次。

一、自訂 View 本體

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.text.Html;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 自訂倒計時文字控制項
 */
public class TimeTextView extends TextView implements Runnable {

    Paint mPaint;                       // 畫筆:包含繪製樣式與顏色資訊
    private long[] times;
    private long mday, mhour, mmin, msecond;  // 天、小時、分鐘、秒
    private boolean run = false;        // 是否已啟動

    public TimeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TimeTextView);
        array.recycle();   // 一定要呼叫,否則這次設定會影響下次使用
    }

    public TimeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mPaint = new Paint();
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TimeTextView);
        array.recycle();
    }

    public TimeTextView(Context context) {
        super(context);
    }

    public long[] getTimes() {
        return times;
    }

    public void setTimes(long[] times) {
        this.times = times;
        mday = times[0];
        mhour = times[1];
        mmin = times[2];
        msecond = times[3];
    }

    /** 倒數一秒,並處理借位 */
    private void ComputeTime() {
        msecond--;
        if (msecond < 0) {
            mmin--;
            msecond = 59;
            if (mmin < 0) {
                mmin = 59;
                mhour--;
                if (mhour < 0) {
                    // 天數也耗盡,倒計時結束
                    mhour = 59;
                    mday--;
                }
            }
        }
    }

    public boolean isRun() {
        return run;
    }

    public void setRun(boolean run) {
        this.run = run;
    }

    @Override
    public void run() {
        run = true;
        ComputeTime();

        String strTime = "還剩<span style=\"color: red;\">" + mday + "</span>"
                + "<pre>天</pre><span style=\"color: red;\">" + mhour + "</span>"
                + "<pre>小時</pre><span style=\"color: red;\">" + mmin + "</span>"
                + "<pre>分鐘</pre><span style=\"color: red;\">" + msecond + "</span>"
                + "<pre>秒";

        this.setText(Html.fromHtml(strTime));
        postDelayed(this, 1000);
    }
}

屬性宣告檔 attrs.xml:

<declare-styleable name="TimeTextView">
</declare-styleable>

二、在 Adapter 中使用

列表裡的每一筆商品都有自己的倒計時,因此這個 View 通常會出現在 Adapter 的 getView 裡。幾個重點:

// 特賣倒計時控制項
viewHolder.mTimeText = (TimeTextView) convertView
        .findViewById(R.id.temai_timeTextView);

...

if (DateTools.isStart(list.get(arg0).getSpecialFrom())) {
    // 特賣已開始,啟動倒計時
    viewHolder.mTimeText.setTimes(
            DateTools.getDate(CorrectSpecialDataFormHttp
                    .correctData(list.get(arg0).getSpecialEnd())));

    // 已經在倒數的話不要重複啟動
    if (!viewHolder.mTimeText.isRun()) {
        viewHolder.mTimeText.run();
    }
    viewHolder.showDate_l.setVisibility(View.GONE);
    viewHolder.showTime.setVisibility(View.VISIBLE);
} else {
    viewHolder.showTime.setVisibility(View.GONE);
    viewHolder.showDate_l.setVisibility(View.VISIBLE);
    viewHolder.showDate.setText(
            DateTools.getDay(list.get(arg0).getSpecialFrom()) + "");
}

由於 ListView 會回收 convertView,因此實作 resetViewHolder() 時記得把倒計時文字一起清掉,避免「A 商品的剩餘時間跑到 B 商品上」這種典型的复用錯亂:

protected void resetViewHolder(ViewHolder viewHolder) {
    viewHolder.image.setImageBitmap(null);
    viewHolder.goodName.setText("");
    viewHolder.price.setText("");
    viewHolder.specialPrice.setText("");
    viewHolder.koukou.setText("");
    viewHolder.mTimeText.setText("");
    viewHolder.showDate.setText("");
}

三、這個實作可以更好的地方

  • 用 postDelayed(this, 1000) 累加會隨時間漂移。正式環境建議改成記錄「目標時間戳」,每次回呼時用 System.currentTimeMillis() 重算剩餘毫秒,這樣即使 App 被切到背景再回來也不會走鐘。
  • View 從版面回收時(onDetachedFromWindow)記得 removeCallbacks(this),否則在長列表裡會累積大量無效回呼。
  • 倒數歸零後應發出事件通知業務層(例如把按鈕切成「已結束」),而不是只在文字上顯示 0。
  • 天 / 時 / 分 / 秒建議拆成獨立的自訂 View 或直接用 GridLayout 排版,比用 HTML 標籤拼字串更好維護,也不必每秒解析一次 HTML。

四、布局片段

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/temai_weikaishi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <TextView ... android:text="距離開始還有" />
        <TextView android:id="@+id/index_temai_day" ... />
        <TextView ... android:text="天" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/temai_yikaishi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        <com.new0315.widgets.TimeTextView
            android:id="@+id/temai_timeTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved