Android:自动向下滚动EditTextView以查找聊天应用

Byt*_*yte 4 android chat autoscroll android-edittext

感谢您的关注,我正在创建一个聊天应用程序.它在很大程度上起作用.我遇到的唯一问题是滚动.我使用EditText从服务器发布新消息.

通过方法

msg = msg + "\n" + newMsg
EditText.setText(msg)
Run Code Online (Sandbox Code Playgroud)

我需要尽快将旧文本下的新文本显示出来.

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

有一个简单的方法吗?喜欢布局吗?

再次感谢!

布局代码

<?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>
Run Code Online (Sandbox Code Playgroud)

sen*_*one 15

解决方案是通过post发送单独的UI消息.这肯定会奏效.将文本/文本附加到ScrollView内的TextView之后,通过post(Runnable)方法更新ScrollView,如下面的代码所示:

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


Jig*_*hua 9

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

<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>
Run Code Online (Sandbox Code Playgroud)

并且在按下要查看的消息后自动向下滚动调用此方法

private void scrollDown() {
        scroller.smoothScrollTo(0, messageView.getBottom());  
}
Run Code Online (Sandbox Code Playgroud)

这里的滚动条是ScrollView,messageView是TextView

您也可以使用HTML打印不同颜色的消息

messageView.append(Html.fromHtml("<font color='green'><b>("+date+") "+ username +":</b></font><br/>"+ message+"<br/>", null, null));
Run Code Online (Sandbox Code Playgroud)