Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 376
Dims Avatar asked Apr 07 '26 13:04

Dims


1 Answers

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);
    }
});
like image 100
Divyesh Patel Avatar answered Apr 09 '26 01:04

Divyesh Patel