android 自定义 数字时钟,android 自定义TextView实现秒级数字时钟

package com.jinhui.humitureshow.view

import android.content.Context

import android.os.Handler

import android.os.Looper

import android.os.Message

import android.util.AttributeSet

import android.widget.TextView

import com.jinhui.humitureshow.R

import java.util.*

/**

* Description: 自定义时间显示TextView,时间取决于当前Android设备的时间

*

* Creator: Shawn

* Data&Time: 2019/1/17 & 13:52

*/

class TimeTextView : TextView {

private val handler: TimeHandler =

TimeHandler(this)

constructor(context: Context) : this(context, null)

constructor(context: Context, set: AttributeSet?) : this(context, set, 0)

constructor(context: Context, set: AttributeSet?, defStyleAttr: Int) : this(context, set, defStyleAttr, 0)

constructor(context: Context, set: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(

context,

set,

defStyleAttr,

defStyleRes

) {

init(context)

}

/**

* 获取当前时间并启动时钟更新线程

*

* @param context Context

*/

private fun init(context: Context) {

updateClock(context)

Thread(Runnable { handler.startScheduleUpdate() }).start()

}

/**

* 更新时钟

*/

private fun updateClock(context: Context) {

val calendar = Calendar.getInstance(TimeZone.getDefault())

val year = calendar.get(Calendar.YEAR)

val month = calendar.get(Calendar.MONTH) + 1

val day = calendar.get(Calendar.DAY_OF_MONTH)

val hour = calendar.get(Calendar.HOUR_OF_DAY)

val minute = calendar.get(Calendar.MINUTE)

val second = calendar.get(Calendar.SECOND)

val dayStr = formatInt(day)

val monthStr = formatInt(month)

val hourStr = formatInt(hour)

val minuteStr = formatInt(minute)

val secondStr = formatInt(second)

val weekStr = getWeak(calendar)

this.text = context.getString(R.string.time_example, year, monthStr, dayStr, weekStr, hourStr, minuteStr, secondStr)

}

/**

* 获取当前星期

* @param calendar Calendar

* @return String

*/

private fun getWeak(calendar: Calendar): String {

val week = calendar.get(Calendar.WEEK_OF_MONTH)

return when (week) {

1 -> "日"

2 -> "一"

3 -> "二"

4 -> "三"

5 -> "四"

6 -> "五"

else -> "六"

}

}

/**

* 格式化 个位数格式

* @param number Int

*/

private fun formatInt(number: Int): String {

return when (number < 10) {

true -> "0$number"

else -> "$number"

}

}

companion object {

private class TimeHandler(private val timeTextView: TimeTextView) : Handler(Looper.getMainLooper()) {

private var mStopped = false

fun post() {

//每隔1秒发送一次消息

sendMessageDelayed(obtainMessage(0), 1000)

}

override fun handleMessage(msg: Message?) {

super.handleMessage(msg)

if (!mStopped) {

timeTextView.updateClock(timeTextView.context)

//实现实时更新

post()

}

}

fun startScheduleUpdate() {

mStopped = false

post()

}

// fun stopScheduleUpdate() {

// mStopped = true

// }

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值