2011-02-24 32 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