简体   繁体   中英

Scroll TextView automatically to last line in Activity when just started

On start of Activity I want TextView been scrolled down to possible last line.

Now when Activity starts I see TextView showing text from top. How I can scroll TextView to the last line and start and show it from bottom?

The code I'm currently using

@Override
    protected void initUI(Bundle savedInstanceState) {
        logTextView = (EditText)findViewById( R.id.text );

        ArrayList<Event> events = getAll();

        StringBuilder sb = new StringBuilder(64*1024);
        for (Event event : events) {
            sb.append( event.toString() );
            sb.append( "\n" );
        }

        logTextView.setText( sb );
        logTextView.setKeyListener(null);
        logTextView.setFocusable(true);
    }

int y = (textView.getLineCount() - 1) * textView.getLineHeight(); // the " - 5" should send it to the TOP of the last line, instead of the bottom of the last line
            int visible = logTextView.getHeight() - (2* logTextView.getLineHeight());
            if( visible < y ) y -= visible;
            logTextView.scrollTo(0, y);

Put the following code after your data is added:

final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
scrollview.post(new Runnable() {
    @Override
    public void run() {
        scrollview.fullScroll(ScrollView.FOCUS_DOWN);
    }
});

At last I found the solution

Here is the code

@Override
    protected void initUI(Bundle savedInstanceState) {
        logTextView = (EditText)findViewById( R.id.text );

        ArrayList<Event> events = getAll();

        StringBuilder sb = new StringBuilder(64*1024);
        for (Event event : events) {
            sb.append( event.toString() );
            sb.append( "\n" );
        }

        logTextView.setText( sb );
        logTextView.setKeyListener(null);
        logTextView.setFocusable(true);

//This line triggers textView to scroll all the way down to the bottom.
logTextView.setSelection(logTextView.getText().length());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM