auto-scrolling TextView in android to bring text into view

前端 未结 13 1706

I have a TextView that I\'m dynamically adding text to.

in my main.xml file I have the properties set to make my max lines 19 and scrollbar

13条回答
  •  感情败类
    2020-11-28 05:26

    Previous answers did not work correctly for me, this however works.

    Create a TextView and do the following:

    // ...
    mTextView = (TextView)findViewById(R.id.your_text_view);
    mTextView.setMovementMethod(new ScrollingMovementMethod());
    // ...
    

    Use the following function to append text to the TextView.

    private void appendTextAndScroll(String text)
    {
        if(mTextView != null){
            mTextView.append(text + "\n");
            final Layout layout = mTextView.getLayout();
            if(layout != null){
                int scrollDelta = layout.getLineBottom(mTextView.getLineCount() - 1) 
                    - mTextView.getScrollY() - mTextView.getHeight();
                if(scrollDelta > 0)
                    mTextView.scrollBy(0, scrollDelta);
            }
        }
    }
    

    Hope this helps.

提交回复
热议问题