Dims
Dims

Reputation: 51019

How to scroll ScrollView to bottom programmatically in Android?

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?

Upvotes: 3

Views: 12044

Answers (2)

Peri Hartman
Peri Hartman

Reputation: 19474

You can try scrolling to Integer.MAX_VALUE

scrollView.scrollTo(0, Integer.MAX_VALUE)

Upvotes: 0

Divyesh Patel
Divyesh Patel

Reputation: 2576

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

Upvotes: 18

Related Questions