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?

Dims
  • 47,675
  • 117
  • 331
  • 600

2 Answers2

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);
    }
});
crgarridos
  • 8,758
  • 3
  • 49
  • 61
Divyesh Patel
  • 2,576
  • 2
  • 15
  • 30
0

scrollView.scrollTo (0, Integer.MAX_VALUE)

Peri Hartman
  • 19,314
  • 18
  • 55
  • 101