Question

I'm working on the following TextView:

<?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/tabsContent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="3dp"
        android:background="@drawable/rounded_edges"
        android:gravity="bottom"
        android:padding="8dp"
        android:scrollHorizontally="false"
        android:scrollbarStyle="insideOverlay"
        android:scrollbars="vertical"
        android:textColor="#FFFFFF"
        android:textSize="11sp"
        android:typeface="monospace" />

This TextView is used to display large amount of data that I get from a Socket, so the content is updated by a background Service. The problem is that after certain amount of text, the scrollbar is enabled and each time I append a line to the TextView, the scrollbar starts to show and fade out every time a new line is appended to the TextView, as its gravity is set to bottom, so it gets annoying for the user.

What I want to achieve is to enable the visibility of the scrollbar only if the user scrolls manually up or down, but haven't found anything so far to implement this. What I've tried is:

  • Setting the android:scrollbars to none in the layout and implement a onClickListener, so it would enable the scrolling to vertical and set to none again on release, but as this event is triggered once the user releases the screen, it didn't work.

  • Same on onLongClickListener, same result as when a new line is appended to the TextView, the layout is set to the bottom of it as the gravity is bottom, so actually this listener is barely triggered.

  • Same on onDragListener, I couldn't even achieve this to trigger, so I guess this is not recognized as a drag action.

  • This class doesn't implement the onScrollListener.

At this point I'm out of ideas on how to implement this, so any advice is appreciated. Thanks.

Was it helpful?

Solution

You can disable the vertical scroll bar before appending new text to the TextView, and post an event to reenable it after the text has been drawn.

Something like this:

textView.setVerticalScrollBarEnabled(false);
textView.append("New Text");
textView.post(new Runnable() {
    @Override
    public void run() {
        textView.setVerticalScrollBarEnabled(true);
    }
});

Of course you should reuse a single Runnable object for enabling the scroll bar, instead of creating a new one on every change to the text.

Note that if you set the TextView gravity to bottom, then it will be constantly scrolled to the bottom whenever the text is changed, regardless of any scrolling done by the user in the interim.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top