在Android中滚动信用文本

时间:2014-04-12 10:23:21

标签: android textview scroll

我需要在游戏中制作一个积分屏幕(Activity)。它只是一个没有任何图像的垂直滚动文本行。滚动将自动执行,不允许用户交互。就像从底部到顶部的电影信用。在最后一个文本行消失在屏幕顶部之后,它应该重新启动。

我该怎么办?仅使用TextView并以某种方式为其设置动画就足够了吗?或者我应该将TextView放入ScrollView?你会建议什么?

1 个答案:

答案 0 :(得分:3)

我正在使用它: -

    /**
 * A TextView that scrolls it contents across the screen, in a similar fashion as movie credits roll
 * across the theater screen.
 *
 * @author Matthias Kaeppler
 */
public class ScrollingTextView extends TextView implements Runnable {

    private static final float DEFAULT_SPEED = 15.0f;

    private Scroller scroller;
    private float speed = DEFAULT_SPEED;
    private boolean continuousScrolling = true;

    public ScrollingTextView(Context context) {
        super(context);
        setup(context);
    }

    public ScrollingTextView(Context context, AttributeSet attributes) {
        super(context, attributes);
        setup(context);
    }

    private void setup(Context context) {
        scroller = new Scroller(context, new LinearInterpolator());
        setScroller(scroller);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (scroller.isFinished()) {
            scroll();
        }
    }

    private void scroll() {
        int viewHeight = getHeight();
        int visibleHeight = viewHeight - getPaddingBottom() - getPaddingTop();
        int lineHeight = getLineHeight();

        int offset = -1 * visibleHeight;
        int totallineHeight = getLineCount() * lineHeight;
        int distance = totallineHeight + visibleHeight;
        int duration = (int) (distance * speed);

        if (totallineHeight > visibleHeight) {
            scroller.startScroll(0, offset, 0, distance, duration);

            if (continuousScrolling) {
                post(this);
            }
        }
    }

    @Override
    public void run() {
        if (scroller.isFinished()) {
            scroll();
        } else {
            post(this);
        }
    }

    public void setSpeed(float speed) {
        this.speed = speed;
    }

    public float getSpeed() {
        return speed;
    }

    public void setContinuousScrolling(boolean continuousScrolling) {
        this.continuousScrolling = continuousScrolling;
    }

    public boolean isContinuousScrolling() {
        return continuousScrolling;
    }
}