Search code examples
androidandroid-layouttextviewandroid-scrollview

Scroll text in a horizontal scroll view


I have seen a few posts similar to my issue. However, the solutions mentioned in those posts did not help me fix the problem. Here is the scenario. I have a TextView in a horizontal scroll view. The idea is as soon as a text (larger than the view) is appended to the TextView, it must be automatically scrolled to end. Here is the layout snippet.

<HorizontalScrollView
             android:id="@+id/horizontalScrollView1"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_margin="5dp"
             android:background="@color/subTitleColor"
             android:fillViewport="true"
             android:scrollbars="none" >

            <TextView
                android:id="@+id/drillPath"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="bottom"
                android:text="this is a such a long text that scrolling is needed, scroll more"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@color/textColorWhite" />

</HorizontalScrollView> 

Upon an event, I do the following.

textView.append("do auto scroll");

Effectively, it should scroll the text to the end. But it isn't! What is it I am lacking?


Solution

  • First of all, your scrollview will never scroll since its content view (the TextView) is in fill_parent mode. it should wrap its content in order to leave space for the text and be bigger than its parent. (change your textView width to : android:layout_width="wrap_content" )

    Then, there is nothing here to request the scroll, I don't think it should happen automatically.

    Add something like this to request the scroll to the end of your scroll view :

       textView.append("do auto scroll");
    
        scrollView.post(new Runnable() {            
            @Override
            public void run() {
                   scrollView.fullScroll(View.FOCUS_RIGHT);              
            }
        });
    

    Let me know when you've tried it.