1

在我的应用程序中,我试图模仿 SMS 消息应用程序的对话视图,其中发送的消息与左边距对齐,接收的消息与右边对齐。我正在使用自定义RelativeLayout来实现左/右对齐,并且我TextView在运行时动态添加 s,方法是在我的 custom 上调用一个方法RelativeLayout

我遇到的问题是,当我添加TextView第一个之后的 s 时,它们被放置在另一个之上(在相同的 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"/>

任何帮助表示赞赏。

谢谢!

4

1 回答 1

1

据我所知,您没有IDsTextViews要添加的内容设置任何内容。所以,当你打电话时:

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)or为您的 TextViews 设置 ID setId(View.generateViewId()),看看这是否有助于解决问题。

于 2013-07-28T01:10:25.900 回答