views:

40

answers:

1

I working on a chat app. Whenever I submit or receive a text message, I append them to the chatbox. When the list get longer, I need to scroll down to see them. How can I make it to autoscroll to the newly append text?

<ScrollView
    android:id="@+id/scrollView01"
    android:layout_width="fill_parent"
    android:layout_height="100px" >
        <TextView
            android:id="@+id/txtChat"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text=""
            />      
</ScrollView>

//

SendMsg.setOnClickListener(new View.OnClickListener() 
{
    public void onClick(View v) 
    {               
        String name = txtName.getText().toString();
        String message = txtMessage.getText().toString();

    if (message.length() > 0) {
            sendMsg(name, message);
            String myMessage = message + "\n";
            tvChat.append(myMessage);
        }
        else
            Toast.makeText(getBaseContext(), 
                "Please enter both name and message.", Toast.LENGTH_SHORT).show();
    }
});  
+4  A: 

I had the same issue, this is what I'm using:

//delay must be expressed in milliseconds. For 3 seconds, delay = 3000
private void scrollToBottom(int delay) {
    // If we don't call fullScroll inside a Runnable, it doesn't scroll to
    // the bottom but to the (bottom - 1)
    mChatBox.postDelayed(new Runnable() {
        public void run() {
            mChatBox.fullScroll(ScrollView.FOCUS_DOWN);
        }
    }, delay);
}

where mChatBox is:

ScrollView mChatBox;
Maragues
And don't forget -> mChatBox = (ScrollView)findViewById(R.id.scrollView);
conandor
just like the rest of the android elements :) That's why I didn't specify it, but thanks for posting it, maybe it helps someone.
Maragues