自定義view實現(xiàn)簡單的計時器

自定義View學習小記

@Alu

先貼代碼

public class CountView extends View {
private Paint mPaint;
private int millisecond;
private int hour;
private int minute;
private int second;
private Rect mBounds;
private Context context;
private boolean isRunning = false;
private Timer timer;
private StringBuffer stringBuffer;
private MyTask myTask;

public CountView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    this.context = context;
    mBounds = new Rect();
    mPaint = new Paint();
    stringBuffer = new StringBuffer();
    stringBuffer.append("00:00:00:00");

}
@Override
public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()){
        case MotionEvent.ACTION_DOWN:
            if (isRunning) {
                timer.cancel();
                timer.purge();
                timer = null;
                myTask = null;
                System.gc();
            } else {
                timer = new Timer();
                myTask = new MyTask();
                timer.schedule(myTask, 0, 10);
            }
            isRunning = !isRunning;
            break;
    }
    return false;
}
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mPaint.setColor(ContextCompat.getColor(context, R.color.colorPrimary));
    canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
    mPaint.setColor(Color.WHITE);
    mPaint.setTextSize(60);
    String text = stringBuffer.toString();
    mPaint.getTextBounds(text, 0, text.length(), mBounds);
    float textWidth = mBounds.width();
    float textHeight = mBounds.height();
    canvas.drawText(text, getWidth() / 2 - textWidth / 2, getHeight() / 2 + textHeight / 2, mPaint);

}

private class MyTask extends TimerTask {

    @Override
    public void run() {
        stringBuffer.delete(0, stringBuffer.length());
        millisecond++;
        if (millisecond > 99) {
            millisecond = 0;
            second++;
        }
        if (second > 59) {
            second = 0;
            minute++;
        }

        if (minute > 59) {
            minute = 0;
            hour++;
        }
        if (hour < 10)
            stringBuffer.append(0).append(hour);
        else
            stringBuffer.append(hour);
        stringBuffer.append(":");
        if (minute < 10)
            stringBuffer.append(0).append(minute);
        else
            stringBuffer.append(minute);
        stringBuffer.append(":");
        if (second < 10)
            stringBuffer.append(0).append(second);
        else
            stringBuffer.append(second);
        stringBuffer.append(":");
        if (millisecond < 10)
            stringBuffer.append(0).append(millisecond);
        else
            stringBuffer.append(millisecond);
        handler.sendEmptyMessage(0);
    }

}

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == 0) {
            invalidate();
        }
    }
};

}
利用Handler+Timer來控制時間,StringBuffer和很簡單的算法來保存時間。
用法很簡單直接在布局中引用:

<com.alu.test.okletusgo.myview.view.CountView
    android:layout_width="150dp"
    android:layout_height="50dp"
    android:layout_centerInParent="true" />

稍加改造也可以有其他用途,例如 在抽獎之類的界面使用.

需要注意的:

view的點擊事件里我做了:

timer = new Timer();  
myTask = new MyTask();

原因是個人多次嘗試,timerrun方法只會執(zhí)行 TimerTask 類的run();方法一次,所以手動去將之前用過的對象設置為 null 并調用 System.gc(); ,企圖回收對象,(感覺很笨,希望有人看了指點一下),再重新去設置一個新的 timer。
另外提一下 Viewinvalidate(); 方法需要在主線程執(zhí)行 ,這也是使用了handler的原因。

最后:

不求贊,只求提出問題,讓我改進學習。

修改暫停繼續(xù)的操作在 onTouch 的 ACTIONDOWN 情境下 。原因是對計時器的精準控制就應該體現(xiàn)在點下去的瞬間來控制跑秒。

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 主要思路 1.我們需要自定義一個繼承自FrameLayout的布局,利用FrameLayout布-局的特性(在同一...
    ZebraWei閱讀 2,748評論 0 5
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,725評論 25 709
  • 周五,我一直在說服自己,只要你想做,就一定能做到。但是發(fā)現(xiàn)自己執(zhí)行力太差,是沒有精神,還是年齡大了,注意力渙散?,F(xiàn)...
    向往的1991閱讀 160評論 0 0
  • 開工一張新的,有誰知道是什么名號嗎?
    joyyang1221閱讀 242評論 0 2
  • 我們沒有義務去感同身受別人的故事和感情 生活,就應該在不傷害他人的基礎上 讓自己活的舒服
    樹郵閱讀 303評論 0 1

友情鏈接更多精彩內(nèi)容