Android自动水平滚动TextView [英] Android automatic horizontally scrolling TextView

查看:27
本文介绍了Android自动水平滚动TextView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个自动滚动的单行文本视图.但不幸的是,我无法让它发挥作用.AutoScrollTextView 在 LinearLayout 中声明(宽度和高度 = fill_parent).该类基本上使用一个 Handler 调用自身以按给定数量滚动.我已将代码简化为仅显示应每秒滚动 5 个像素的文本视图.

I am trying to implement a single-line text view that will scroll automatically. But I unfortunatly cannot get it to work. The AutoScrollTextView is declared inside a LinearLayout (width and height = fill_parent). The class basically uses a Handler that calls itself to scroll by a given amount. I have simplified the code to only show a text view that should be scrolling by 5 pixels every second.

日志输出正确,getScrollX()方法返回合适的scrollX位置.

The log output is correct, the getScrollX() method returns the appropriate scrollX position.

如果我不调用 requestLayout(),则不会绘制任何内容.invalidate() 无效.

If I don't call requestLayout(), nothing gets drawn. invalidate() has no effect.

有人知道吗?

public class AutoScrollTextView extends TextView {

    public AutoScrollTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setSingleLine();
        setEllipsize(null);
        setText("Single-line text view that scrolls automatically if the text is too long to fit in the widget");
    }

    // begin to scroll the text from the original position
    public void startScrolling() {
        scrollHandler.sendEmptyMessage(0);
    }

    private Handler scrollHandler = new Handler() {
        private static final int REFRESH_INTERVAL = 1000;

        public void handleMessage(Message msg) {
            scrollBy(5, 0);
            requestLayout();
            Log.debug("Scrolled to " + getScrollX() + " px");
            sendEmptyMessageDelayed(0, REFRESH_INTERVAL);
        }
    };
}

推荐答案

如果你不需要对 TextView 进行子类化,你可以在你的布局文件中试试这个:

If you don't need to sub-class the TextView, you can try this in your layout file:

    <TextView
        android:text="Single-line text view that scrolls automatically if the text is too long to fit in the widget" 
        android:singleLine="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit ="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true" 
        android:scrollHorizontally="true"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"/>

此外,在您的代码中使用以下内容:

Also, in your code use the following:

findViewById(R.id.serviceColorCode).setSelected(true);

[根据评论编辑答案]

这篇关于Android自动水平滚动TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆