Reputation: 679
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:
Upvotes: 1
Views: 9924
Reputation: 1
first - Make a style.xml
<style name="VerticalScrollableTextView">
<item name="android:scrollbars">vertical</item>
<item name="android:scrollbarFadeDuration">0</item>
</style>
second - use ContextWrapper
val textView = TextView(
ContextThemeWrapper(context, R.style.VerticalScrollableTextView)
)
textView.movementMethod = ScrollingMovementMethod.getInstance()
That's All!
Upvotes: 0
Reputation: 2336
Show only when scroll
Xml (in textView element):
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="vertical"
OnCreate:
textView.movementMethod = ScrollingMovementMethod()
Upvotes: -1
Reputation: 24848
// try this
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = new TextView(this);
textView.setText("demotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotextdemotext");
textView.setVerticalScrollBarEnabled(true);
textView.setLines(3);
textView.setMovementMethod(new ScrollingMovementMethod());
addContentView(textView,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
Upvotes: 2
Reputation: 679
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();
}
}
Upvotes: 6