2013-07-28 105 views
1

在我的應用程序中,我試圖模擬SMS消息傳遞應用程序的對話視圖,其中發送的消息與左邊距對齊,並且收到的消息與右邊對齊。我使用自定義RelativeLayout來實現左右對齊,並且我在運行時動態添加TextView,方法是調用我自定義的RelativeLayout上的方法。在RelativeLayout中以編程方式堆疊子視圖

我遇到的問題是,因爲我添加了第一個後面的TextView,它們被放置在另一個之上(在相同的x,y上),而不是垂直堆疊(增加y)。

這裏是我的代碼,添加TextView

TextView txt = new TextView(mContext); 
RelativeLayout.LayoutParams params = 
    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
            LayoutParams.WRAP_CONTENT); 
params.addRule(sent ? ALIGN_PARENT_LEFT : ALIGN_PARENT_RIGHT); 

// make sure this message is positioned below the last one 
if (getChildCount() > 0) { 
    params.addRule(BELOW, getChildAt(getChildCount() - 1).getId()); 
} 

txt.setLayoutParams(params); 
txt.setText(msg); 

addView(txt); 

我定製RelativeView正是如此定義:

<com.foo.bar.ConversationLayout 
     android:id="@+id/loConvo" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 

任何幫助表示讚賞。

謝謝!

+1

垂直方向的LinearLayout包裝在ScrollView中將爲您提供最好的服務。 – Vikram

+0

您可能最好使用具有兩種不同行佈局的ListView(一個用於發送,一個用於接收)。 – Karakuri

+0

感謝評論@Karakuri,但是@vikram指出,我認爲最簡單的方法(這就是我最終做的)是一個帶有'TextView'子元素的'LinearLayout',''gravity'屬性被設置爲'LEFT'或「RIGHT」,具體取決於消息是發送還是接收。 –

回答

1

從我可以看到的是,你沒有設置任何IDs爲你添加的TextViews。所以,當你撥打:

params.addRule(BELOW, getChildAt(getChildCount() - 1).getId()); 

getId()回報NO_ID

來自View的文檔類:getId() returns a positive integer used to identify the view or NO_ID if the view has no ID

NO_ID is used to mark a View that has no ID

嘗試使用setId(yourGivenId)setId(View.generateViewId())設置ID到您的TextViews,看看是否有助於解決問題。

+0

謝謝!我沒有意識到ID沒有自動設置。我正在研究API版本14,它沒有'View.generateViewId()'靜態方法,但是通過在我的類中添加遞增計數器,我能夠實現相同的結果。 –

相關問題