背景
按照產(chǎn)品設(shè)計(jì),文字過長(zhǎng)時(shí),需要采用跑馬燈顯示. 如果是多行文字上下左右切換的跑馬燈,可以參考《安卓實(shí)現(xiàn)多行文字跑馬燈效果》.
@ 實(shí)現(xiàn)效果圖
實(shí)現(xiàn)方案
class MarqueeTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null)
: AppCompatTextView(context, attrs) {
init {
//設(shè)置單行
setSingleLine()
//設(shè)置Ellipsize
ellipsize = TextUtils.TruncateAt.MARQUEE
//獲取焦點(diǎn)
isFocusable = true
//走馬燈的重復(fù)次數(shù),-1代表無限重復(fù)
marqueeRepeatLimit = -1
//強(qiáng)制獲得焦點(diǎn)
isFocusableInTouchMode = true
}
/*
*這個(gè)屬性這個(gè)View得到焦點(diǎn),在這里我們?cè)O(shè)置為true,這個(gè)View就永遠(yuǎn)是有焦點(diǎn)的
*/
override fun isFocused(): Boolean {
return true
}
/*
* 用于EditText搶注焦點(diǎn)的問題
* */
override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
if (focused) {
super.onFocusChanged(focused, direction, previouslyFocusedRect)
}
}
/*
* Window與Window間焦點(diǎn)發(fā)生改變時(shí)的回調(diào)
* */
override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
if (hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus)
}
}
}
完整源代碼
https://gitee.com/cxyzy1/marqueeView.git