简体   繁体   English

以编程方式在RelativeLayout中堆叠子视图

[英]Programmatically stack child views in RelativeLayout

In my app I'm trying to mimic an SMS messaging application's conversation view where sent messages align to the left margin, and received messages align to the right. 在我的应用程序中,我试图模仿SMS消息传递应用程序的对话视图,在该视图中,已发送的消息与左边距对齐,而接收到的消息与右边距对齐。 I'm using a custom RelativeLayout to achieve the left/right alignment, and I'm adding the TextView s dynamically at runtime, by calling a method on my custom RelativeLayout . 我使用自定义RelativeLayout实现左右对齐,并通过在自定义RelativeLayout上调用方法在运行时动态添加TextView

The problem I'm having is that as I'm adding the TextView s that follow the first one, they are being placed one on top of the other (at the same x,y) instead of being stacked vertically (increasing y). 我遇到的问题是,当我在第一个之后添加TextView ,它们被一个放在另一个(相同的x,y)上,而不是垂直堆叠(增加y)。

Here's my code that adds the TextView : 这是添加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);

My custom RelativeView is defined thusly: 我的自定义RelativeView定义如下:

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

Any help is appreciated. 任何帮助表示赞赏。

Thanks! 谢谢!

From what I can see is that you are not setting any IDs for the TextViews you are adding. 从我可以看到的是,您没有为要添加的TextViews设置任何IDs So, when you call: 因此,当您致电:

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

getId() returns NO_ID . getId()返回NO_ID

From documentation on View class: getId() returns a positive integer used to identify the view or NO_ID if the view has 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 . NO_ID is used to mark a View that has no ID

Try setting IDs to your TextViews using either setId(yourGivenId) or setId(View.generateViewId()) and see if that helps solve the problem. 尝试使用setId(yourGivenId)setId(View.generateViewId())为您的TextView设置ID,然后查看是否有助于解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM