Android:聊天应用程序中的自动滚动编辑文本视图

6
感谢您的关注, 我正在创建一个聊天应用程序。它大部分功能都可以正常运行。 唯一的问题是滚动。 我使用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>
3个回答

16

一个解决方案是通过post发送单独的UI消息。这样一定会有效。在你向ScrollView中的TextView设置文本/追加文本之后,通过post(Runnable)方法更新ScrollView,如下所示的代码:

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

1
这个代码可以滚动到底部!使用Jignesh的XML布局https://dev59.com/2lTTa4cB1Zd3GeqPuKB9#5101616,然后使用SenorCarbone上面的代码。 - Someone Somewhere

11

我认为最好的方法是使用带滚动条的 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));

做那样很好,但我使用EditText,因为我喜欢它的方框外观。 我还将其设置为不可编辑或不可点击。我一直在尝试使用您的解决方案使其正常工作,但似乎我的布局是相对布局,这与其他部分不兼容。 或者可能是我没有正确操作。请查看我的布局。谢谢! - Byte
1
我真是太傻了!我应该仔细看,它是append而不是setText让它工作的!!现在它不会到最后一个,而是倒数第二个.. 有任何评论吗? - Byte
感谢您接受答案,您也可以使用HTML.formHTML()附加表情。 - Jignesh Dhua
尝试。scroller.smoothScrollTo(0,messageView.getBottom()+5000); - Jignesh Dhua

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接