前言
Android 的 TextView
雖然有屬性 android:ellipsize="marquee"
有文字滾動效果,但是坑多,比如焦點變化了就不動了,而且不能控制滾動的速度,在RecyclerView
里的表現更是災難級的。為了解決以上問題,所以就有了MarqueeTextView
:一個由 Kotlin 實現的文本滾動自定義 View。MarqueeTextView: Kotlin 實現文本橫向滾動,跑馬燈效果。 (gitee.com)
相關屬性
xml 屬性
屬性 | 說明 |
---|---|
android:textSize | 文字大小 |
android:textColor | 文字顏色 |
android:text | 文本內容 |
marqueeRepeat | 循環模式:singe -單次執行;singleLoop -單項循環;fillLoop -填充循環 |
marqueeItemDistance | 每個item之間的距離, marqueeRepeat=fillLoop 有效 |
marqueeStartLocationDistance | 開始的起始位置 按距離控件左邊的百分比 0~1之間 |
marqueeSpeed | 文字滾動速度 |
marqueeResetLocation | 重新改變內容的時候 , 是否初始化 位置,默認為true,改變 |
主要方法
start
: 滾動開始stop
: 滾動停止toggle
: 切換滾動開始/停止
使用方式
<com.xin.marquee.text.view.MarqueeTextView
android:id="@+id/tv1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="16dp"
android:text="Kotlin 實現文本橫向滾動,跑馬燈效果。"
android:textSize="14dp"
app:marqueeRepeat="fillLoop"
app:marqueeSpeed="5" />
代碼里調用start
方法
具體實現
讓文字滾動起來其實就是定時在短時間內把文來,這樣看着就會有連續滾動的感覺。
下面僅說明實現效果的核心方法,源碼自取:MarqueeTextView: Kotlin 實現文本橫向滾動,跑馬燈效果。 (gitee.com)
- 核心類:
android.text.TextPaint
和android.os.handler
- 獲取繪制文本的寬度
private fun getTextWidth(text: String?): Float {
if (text.isNullOrEmpty()) {
return 0f
}
return textPaint.measureText(text)
}
- 填充循環模式下的文本拼接
if (repeat == REPEAT_FILL_LOOP) {
mFinalDrawText = ""
//計算文本的寬度
mSingleContentWidth = getTextWidth(targetContent)
if (mSingleContentWidth > 0) {
// 最大可見內容項數
val maxVisibleCount = ceil(width / mSingleContentWidth.toDouble()).toInt() + 1
repeat(maxVisibleCount) {
mFinalDrawText += targetContent
}
}
contentWidth = getTextWidth(mFinalDrawText)
}
- 繪制文本內容
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// 忽略部分代碼 ...
// 繪制文本
if (mFinalDrawText.isNotBlank()) {
canvas.drawText(mFinalDrawText, xLocation, height / 2 + textHeight / 2, textPaint)
}
}
- 定時繪制內容——滾起來
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
if (msg.what == WHAT_RUN) {
mRef.get()?.apply {
if (speed > 0) {
xLocation -= speed
invalidate()
// 50 毫秒繪制一次
sendEmptyMessageDelayed(WHAT_RUN, 50)
}
}
}
}
總結
整個實現下來總的來說還是比較簡單的,能夠滿足平時文本滾動(跑馬燈)效果的需求了。代碼量很少的,也比較清晰,大家看下源碼應該就清楚了。有不清楚的歡迎交流。