安卓开发Android开发经验谈安卓开发

安卓实现单行文字跑马灯效果

2019-08-07  本文已影响14人  蓝不蓝编程

背景

按照产品设计,文字过长时,需要采用跑马灯显示. 如果是多行文字上下左右切换的跑马灯,可以参考《安卓实现多行文字跑马灯效果》.
@ 实现效果图

实现方案

class MarqueeTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null)
    : AppCompatTextView(context, attrs) {

    init {
        //设置单行
        setSingleLine()
        //设置Ellipsize
        ellipsize = TextUtils.TruncateAt.MARQUEE
        //获取焦点
        isFocusable = true
        //走马灯的重复次数,-1代表无限重复
        marqueeRepeatLimit = -1
        //强制获得焦点
        isFocusableInTouchMode = true
    }

    /*
     *这个属性这个View得到焦点,在这里我们设置为true,这个View就永远是有焦点的
     */
    override fun isFocused(): Boolean {
        return true
    }

    /*
     * 用于EditText抢注焦点的问题
     * */
    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        if (focused) {
            super.onFocusChanged(focused, direction, previouslyFocusedRect)
        }
    }

    /*
     * Window与Window间焦点发生改变时的回调
     * */
    override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
        if (hasWindowFocus) {
            super.onWindowFocusChanged(hasWindowFocus)
        }
    }
}

完整源代码

https://gitee.com/cxyzy1/marqueeView.git

附录

  1. 安卓实现多行文字跑马灯效果
  2. 参考资料:
    Android之跑马灯详解
    Android中实现跑马灯效果
上一篇 下一篇

猜你喜欢

热点阅读