0

我已经搜索并搜索以找到如何向 TextView 添加垂直(或水平)滚动条的答案,而无需使用 XML 来添加以下行:android:scrollbars="vertical"。

必须有一种以编程方式执行此操作的方法,不需要将其粘贴在另一个 ScrollView 中。

我刚刚发现了如何以及因为我对此感到兴奋并想帮助其他遇到同样问题的人,这里是:

4

4 回答 4

5

Rusian Yanchyshyn,在他的Android 答案中发布了关键:在 Canvas-Based View 上启用滚动条

在匿名类和初始化块的帮助下,我们现在可以执行以下操作:

            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();                        
                }
            }
于 2013-10-29T03:51:19.130 回答
1
// 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));
}
于 2013-10-29T04:18:19.150 回答
0

仅在滚动时显示

Xml(在 textView 元素中):

android:scrollbarAlwaysDrawVerticalTrack="true" 
android:scrollbars="vertical"

创建时:

textView.movementMethod = ScrollingMovementMethod()
于 2020-12-14T16:10:50.390 回答
0

首先 - 制作一个 style.xml

<style name="VerticalScrollableTextView">
    <item name="android:scrollbars">vertical</item>
    <item name="android:scrollbarFadeDuration">0</item>
</style>

第二 - 使用 ContextWrapper

val textView = TextView(
        ContextThemeWrapper(context, R.style.VerticalScrollableTextView)
    )
    textView.movementMethod = ScrollingMovementMethod.getInstance()

就这样!

于 2021-01-06T08:33:55.113 回答