2011-02-24 66 views
4

感谢您的关注, 我正在创建一个聊天应用程序。它适用于大部分。 我遇到的唯一问题是滚动。 我使用EditText从服务器发布新消息。Android:自动向下滚动EditTextView以获取聊天应用程序

的方法

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> 

回答

15

解决方案是通过邮件发送单独的UI消息。 这肯定会工作。 你之后的setText /文本追加到您的TextView了滚动 更新通过类似下面的代码后(Runnable接口)方法的滚动型内:

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

这可以一直滚动到底部!使用Jignesh的XML布局http://stackoverflow.com/questions/5101448/android-auto-scrolling-down-the-edittextview-for-chat-apps/5101616#5101616然后SenorCarbone的代码如上。 – 2011-11-18 04:41:49

8

我觉得做滚动,而不是这的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> 

,并自动向下滚动呼叫推消息后,这个方法来查看

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

这里滚轮是滚动型和消息查看是TextView的

您还可以使用HTML打印具有不同颜色的邮件,如

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

这样做是非常好的,但我使用EditText,因为我喜欢盒子的外观。我也使它不可编辑也不可点击。我一直试图让你的解决方案适用,但看起来我的布局是相对布局,并且与其他布局不一致。或者我可能做得不对。请看看我的布局。谢谢! – Byte 2011-02-24 08:01:50

+1

我很蠢!我应该仔细观察,这是附加的,而不是setText,使它工作!现在它不会下降到最后一个,但倒数第二..任何评论? – Byte 2011-02-28 08:17:22

+0

感谢您接受ans,您也可以使用HTML.formHTML追加微笑() – 2011-02-28 11:55:03