Search code examples
androidscrolltextviewscrollview

How to show scrollbars on a TextView programmatically


I have searched and searched to find an answer to how to add a vertical (or horizontal) scrollbar to a TextView without having to use the XML just to add the line: android:scrollbars="vertical".

There has to be a way to do this programmatically that doesn't require sticking this within another ScrollView.

I've just found out how and because I am way to excited about this and want to help anyone else who is stuck with the same question, here it is:


Solution

  • Rusian Yanchyshyn, posted the key in his answer at Android: Enable Scrollbars on Canvas-Based View

    With the help of an anonmous class & an initializer block we can now do the following:

                TextView textViewWithScrollBars = new TextView(context)
                {
                    {
                        setVerticalScrollBarEnabled(true);
                        setMovementMethod(ScrollingMovementMethod.getInstance());
                        setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
    
                        // Force scrollbars to be displayed.
                        TypedArray a = this.getContext().getTheme().obtainStyledAttributes(new int[0]);
                        initializeScrollbars(a);
                        a.recycle();                        
                    }
                }