自定义跑马灯首尾间距的 TextView

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gdeer/article/details/88258164

一、效果

普通 TextView 的跑马灯效果:
在这里插入图片描述
MarqueeTextView 的跑马灯效果:
在这里插入图片描述

二、思路

TextView 的跑马灯效果不支持设置首尾间距。查看源码发现,它的跑马灯效果由内部类 Marquee 实现,Marquee 的 start() 方法中启动了跑马灯。

void start(int repeatLimit) {
    if (repeatLimit == 0) {
        stop();
        return;
    }
    mRepeatLimit = repeatLimit;
    final TextView textView = mView.get();
    if (textView != null && textView.mLayout != null) {
        mStatus = MARQUEE_STARTING;
        mScroll = 0.0f;
        final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft()
                - textView.getCompoundPaddingRight();
        final float lineWidth = textView.mLayout.getLineWidth(0);
        final float gap = textWidth / 3.0f;
        mGhostStart = lineWidth - textWidth + gap;
        mMaxScroll = mGhostStart + textWidth;
        mGhostOffset = lineWidth + gap;
        mFadeStop = lineWidth + textWidth / 6.0f;
        mMaxFadeScroll = mGhostStart + lineWidth + lineWidth;

        textView.invalidate();
        mChoreographer.postFrameCallback(mStartCallback);
    }
}

可以看出,gap 就是用来设置首尾间距的,这里默认是文字长度的三分之一。

gap 没有提供可设置的方法,于是想到反射来改变这个值。但是反射拿不到临时变量。又发现 gap 的值影响到的有四个成员变量 mGhostStartmMaxScrollmGhostOffsetmMaxFadeScroll,那么反射修改这四个值就可以。

start() 方法最后调了 mChoreographer.postFrameCallback(mStartCallback),之后会走到 tick() 方法,tick() 方法里会调用 textView.invalidate() 来进行刷新,跑马灯效果就是通过不断重绘而形成的。

那么我们只要重写 invalidate() 方法,在 super.invalidate() 之前反射修改掉四个成员变量的值就好。

三、源码

https://github.com/Gdeeer/MarqueeTextView

猜你喜欢

转载自blog.csdn.net/Gdeer/article/details/88258164