Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

scroll - Android automatic horizontally scrolling TextView

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.

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

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

Would anybody have a clue?

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);
        }
    };
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

[Answer edited based on comments]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...