2013-05-19 85 views
0

我正在构建一个非常简单的在线聊天室应用程序。我所实现的是类似下面现在:在Android中建立一个简单的群聊聊天视图

Robert:blah.. 
Tom: yes blah.. 
David(You): That sounds cool! 
Lily: Do you know blah... 
Robert:blah.. 
Robert:blah.. 
David(You): Wow! Blah... 

我面临的新功能/问题是,我想当前用户的会谈,以显示在右边。 像下面(这是大卫看到他的屏幕上):

Robert:blah.. 
Tom: yes blah.. 
            That sounds cool! : David(You) 
Lily: Do you know blah... 
Robert:blah.. 
Robert:blah.. 
             Wow! Blah... : David(You) 

上面的每一行是一个TextView,而我动态创建的TextView每当有新的消息,然后将它们添加到包含这些的TextView的LinearLayout 。为了让大卫(当前用户)在右边的讲话,我试图设置对齐,我将LinearLayout改为RelativeLayout。但后来我意识到,一旦我使用RelativeLayout,所有会谈都在同一行中重叠,因为我没有设置它们的高度。任何人都可以阐明如何实现这一目标吗?我的代码如下:

...  
//new messages are stored in lines[] 
for (int i = 0; i < lines.length; i++) { 

    TextView newLine = new TextView(getBaseContext()); 

    newLine.setText(lines[i]); 

    // check if the speaker of this line is user himself    
    if (speakerName.equals(userName)) { 

    //change the layout of this textView to make it align right.. 

    } 
    myLinearView.addView(newLine);//add to linearView that contains these talks 
} 
+0

你应该考虑使用listview,以这种方式追加textview会消耗大量的内存。 –

回答

2

你肯定需要使用ListView,就像Chor WaiChun提到的那样。然而,用相对布局来做这件事的方法是用一个规则设置该视图的RelativeLayout.layoutParams,该规则将其设置为layout_below之前的视图。就像你在XML中一样。另外,即使你坚持每行添加1个视图(如前所述是错误的,使用ListView),没有理由不使用LinearLayout。您可以使用右对齐文本的LinearLayout,只需将重力设置为右。