我正在显示文本的TextView,似乎太长,以适合 在一个屏幕上。我需要使我的TextView可滚动。我该怎么办 了吗?

代码如下:

final TextView tv = new TextView(this);
tv.setBackgroundResource(R.drawable.splash);
tv.setTypeface(face);
tv.setTextSize(18);
tv.setTextColor(R.color.BROWN);
tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL);
tv.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        Random r = new Random();
        int i = r.nextInt(101);
        if (e.getAction() == e.ACTION_DOWN) {
            tv.setText(tips[i]);
            tv.setBackgroundResource(R.drawable.inner);
        }
        return true;
    }
});
setContentView(tv);

当前回答

上面的“专业提示”从某人某处(使TextView可滚动的Android)工作很好,然而,如果你动态添加文本到ScrollView,并希望自动滚动到底部后追加,只有当用户在ScrollView底部?(也许是因为如果用户已经向上滚动阅读了一些内容,你不想在追加过程中自动重置到底部,这很烦人。)

总之,是这样的:

if ((mTextStatus.getMeasuredHeight() - mScrollView.getScrollY()) <=
        (mScrollView.getHeight() + mTextStatus.getLineHeight())) {
    scrollToBottom();
}

mTextStatus.getLineHeight()将使你不scrollToBottom()如果用户是在一行从ScrollView的结束。

其他回答

你可以

环绕TextView由一个ScrollView;或 将移动方法设置为ScrollingMovementMethod.getInstance();。

我发现最好的方法是:

用带有这些额外属性的EditText替换TextView:

android:background="@null"
android:editable="false"
android:cursorVisible="false"

不需要在ScrollView中进行包装。

把maxLines和滚动条内TextView在xml。

<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="vertical"
    android:maxLines="5" // any number of max line here.
    />

然后是java代码。

textView。setMovementMethod(新ScrollingMovementMethod ());

在kotlin使textview可滚动

myTextView.movementMethod= ScrollingMovementMethod()

并在XML中添加这个属性

    android:scrollbars = "vertical"

这将提供一个滚动条平滑滚动文本。

ScrollView scroller = new ScrollView(this);
TextView tv = new TextView(this);
tv.setText(R.string.my_text);
scroller.addView(tv);