Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Android control for displaying scrollable multiline text

I'm starting to write an ebook type of program in Android and don't know the best alternative to Apple's UITextView.

It needs to display multiline read-only text and be scrollable.

like image 869
McGafter Avatar asked May 19 '26 00:05

McGafter


1 Answers

You already know this class - it is TextView - you can adjust it to be scrollable.

In XML view template put android:scrollbars="vertical":

<TextView 
    android:id="@+id/myText"
    android:scrollbars="vertical"

In java code put then:

mTextView = (TextView) findViewById(R.id.myText);
mTextView.setMovementMethod(ScrollingMovementMethod.getInstance());

If you want your TextView to scroll automatically to the bottom after the text is changed, add the code like below:

mTextView.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        scrollToLastLine(mTextView);
    }

    private void scrollToLastLine(TextView tv) {
        int scrollY = 0;
        if (!TextUtils.isEmpty(tv.getText())) {
            final int linesCount = tv.getLineCount();
            if (linesCount > 0) {
                scrollY = Math.max(0,
                        tv.getLayout().getLineTop(linesCount)
                                - tv.getHeight());
            }
        }
        tv.scrollTo(0, scrollY);
    }
});
like image 53
Tomasz Gawel Avatar answered May 28 '26 09:05

Tomasz Gawel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!