Best Android control for displaying scrolling multiline text

I am starting to write an ebook type program in Android and have no idea of ​​a better Apple UITextView alternative.

It should display read-only multi-line text and scroll.

+3


source to share


1 answer


You already know this class - this TextView

is - you can set it to scroll.

In your XML template, put android:scrollbars="vertical"

:

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

      

In java code enter:



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

      

If you want yours to TextView

automatically scroll down after changing the text, add the following code:

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);
    }
});

      

+3


source







All Articles