Automatic horizontal scroll in TextView

Veljko picture Veljko · Feb 23, 2012 · Viewed 12.4k times · Source

I have custom gallery. Gallery represents items that are frame layout. There are one imageView and textView above it.

If text in textView is too long, i need it to be scrolled automatically. It's one line of text, and it's needed to be scrolled horizontally.

I've found this snippet of code:

TextView
    android:text="Single-line text view that scrolls automatically"       
    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"/>   

It works in my test app with only one text view in it. But it doesn't work in my gallery. Noting happens, text just stay still.

Any help?

Answer

Kai picture Kai · Mar 14, 2012

Try this custom TextView class:

public class AutoScrollingTextView extends TextView {
    public AutoScrollingTextView(Context context, AttributeSet attrs,
            int defStyle) {
        super(context, attrs, defStyle);
    }

    public AutoScrollingTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoScrollingTextView(Context context) {
        super(context);
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction,
            Rect previouslyFocusedRect) {
        if (focused) {
            super.onFocusChanged(focused, direction, previouslyFocusedRect);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean focused) {
        if (focused) {
            super.onWindowFocusChanged(focused);
        }
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}

and set the following XML attributes:

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

This works beautifully in my dictionary apps where multiple entries may need to auto-scroll simultaneously to display complete content.