5

感谢您的关注,我正在创建一个聊天应用程序。它在大多数情况下都有效。我唯一遇到的问题是滚动。我使用EditText从服务器发布新消息。

按方法

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

我需要使旧文本下的新文本一出现就可见。

所以我认为最好的方法是在视图更新后立即自动向下滚动到底部。

有没有简单的方法可以做到这一点?像布局一样?

再次感谢!

布局代码

<?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>
4

3 回答 3

16

一种解决方案是通过 post 发送单独的 UI 消息。那肯定会奏效。在 ScrollView 中将文本/附加文本设置到 TextView 后,通过 post(Runnable) 方法更新 ScrollView,如下面的代码:

messageView.append(blabla);      
scroller.post(new Runnable() { 
                public void run() { 
                    scroller.smoothScrollTo(0, messageView.getBottom());
                } 
            }); 
于 2011-03-01T13:18:03.987 回答
10

我认为最好的方法是使用带有滚动条的 TextView 而不是 EditText,因为一旦消息打印用户无法编辑它。尝试这样的事情,这是打印消息的好方法

<ScrollView android:id="@+id/scroller"
        android:layout_width="fill_parent" android:layout_height="fill_parent"

        android:background="#FFFFFF">
        <TextView android:id="@+id/messageView"
            android:layout_height="fill_parent" android:layout_width="fill_parent"
            android:paddingBottom="8dip" android:background="#ffffff"
            android:textColor="#000000" />
    </ScrollView>

并在推送消息查看后自动向下滚动调用此方法

private void scrollDown() {
        scroller.smoothScrollTo(0, messageView.getBottom());  
}

这里 scroller 是 ScrollView 而 messageView 是 TextView

您还可以使用 HTML 打印不同颜色的消息,例如

messageView.append(Html.fromHtml("<font color='green'><b>("+date+") "+ username +":</b></font><br/>"+ message+"<br/>", null, null));
于 2011-02-24T07:26:42.833 回答
1

试试这个方法: 以编程方式滚动 EditText

于 2011-02-24T07:05:31.443 回答