Android: auto scrolling down the EditTextView for chat apps

Byte picture Byte · Feb 24, 2011 · Viewed 18.7k times · Source

Thank you for looking, I am creating a chat application. It works for the most part. The only thing I have a problem with is the scrolling. I use EditText to publish the new message from the server.

by method

msg = msg + "\n" + newMsg
EditText.setText(msg)

I need to make the new text that is under the old text visible as soon as it comes.

So I think best way is to auto scroll down to the bottom as soon as the view is updated.

Is there an easy way to do that? like in layout maybe?

Thanks again!

code for layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="send"
/>
    <EditText
android:id="@+id/msgBox"
android:layout_height="wrap_content" 
android:layout_width="fill_parent" 
android:layout_alignParentBottom="true" 
android:layout_toLeftOf="@+id/sendButton"
android:gravity="left"
android:longClickable="false"
/>
<EditText  
android:id="@+id/chatBox"
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:editable="false"
android:layout_above="@+id/msgBox"
android:scrollbars="vertical" 
android:gravity="left|top" 
android:isScrollContainer="true" 
android:cursorVisible="false" 
android:longClickable="false" 
android:clickable="false"
android:autoLink="all"
/>
</RelativeLayout>

Answer

senorcarbone picture senorcarbone · Mar 1, 2011

A solution is to send a seperate UI message via post. That will definitely work. After you setText/append text to your TextView inside the ScrollView update the ScrollView via the post(Runnable) method like the code below:

messageView.append(blabla);      
scroller.post(new Runnable() { 
                public void run() { 
                    scroller.smoothScrollTo(0, messageView.getBottom());
                } 
            });