3

How to scroll ScrollView to bottom programmatically in Android?

The proposed code

logScroll.scrollTo(0, logScroll.getBottom());

doesn't work (scrolls to bottom where it was at the beginning, not at actual bottom).

Layout is follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.inthemoon.trylocationlistener.MainActivity">

    <ScrollView
        android:id="@+id/log_scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/log_text"

            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </ScrollView>


</RelativeLayout>

populating code is follows:

@BindView(R.id.log_scroll)
    ScrollView logScroll;

    @BindView(R.id.log_text)
    TextView logText;

    private void log(String msg) {
        logText.append(new SimpleDateFormat( "HH:mm:ss ", Locale.US ).format(new Date()) + msg + "\n");
        logScroll.scrollTo(0, logScroll.getBottom());
    }

UPDATE

I read some answers and wrote:

private void log(String msg) {
        logText.append(new SimpleDateFormat( "HH:mm:ss ", Locale.US ).format(new Date()) + msg + "\n");
        //logScroll.scrollTo(0, logScroll.getBottom());
        logScroll.fullScroll(View.FOCUS_DOWN);
    }

why is it worse than using post?

2
  • getBottom() is a View method. The anchor of the XML. You want to get to the bottom of the viewport? Commented Jan 24, 2017 at 14:07
  • 3
    stackoverflow.com/a/4524131/2435238 Commented Jan 24, 2017 at 14:09

2 Answers 2

18

Use this when you want to scroll to bottom with a softkeyboard event:

scrollView.postDelayed(new Runnable() {
    @Override
    public void run() {
         scrollView.fullScroll(ScrollView.FOCUS_DOWN);
    }
}, 100);

And instant scroll:

scrollView.post(new Runnable() {
    @Override
    public void run() {
        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can try scrolling to Integer.MAX_VALUE

scrollView.scrollTo(0, Integer.MAX_VALUE)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.