Android Kotlin TextView跑马灯效果

有时候我们在xml中配置跑马灯属性,最后却发现有时有效果,而有时却没有效果,这是为什么呢。

我们大概是如此配置的

android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"

这样配置是没有问题的,问题出在TextView上面,因为TextView焦点丢失了。

提示:maxLines属性不支持跑马灯


解决方案(来自阿里):

只需要重写父类方法IsFocused(),返回true,即可解决

override fun isFocused(): Boolean {
    return true
}


使用方法:与正常TextView使用方式相同

<com.example.work.myapplication.TextViewAlwaysMarquee
    android:id="@+id/marquee"
    android:layout_width="match_parent"
    android:text="Start123132132132132132132132132132132132123123End"
    android:layout_height="wrap_content" />


class源码

/**
 * Created by work on 2017/8/30.
 * 跑马灯
 * @author chris zou
 * @mail [email protected]
 */
open class TextViewMarquee : AppCompatTextView {
    constructor(context: Context) : super(context)

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)

    override fun isFocused(): Boolean {
        return true
    }
}

自动配置,无需在xml进行配置

/**
 * Created by work on 2017/8/30.
 * 跑马灯-无限循环
 * @author chris zou
 * @mail [email protected]
 */
class TextViewAlwaysMarquee : TextViewMarquee {

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
        init()
    }

    override fun isFocused(): Boolean {
        return true
    }

    private fun init() {
        ellipsize = TextUtils.TruncateAt.MARQUEE
        marqueeRepeatLimit = -1
        setSingleLine()
    }
}




猜你喜欢

转载自blog.csdn.net/Fy993912_chris/article/details/77703220