Reputation: 3122
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. 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
.
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).
Here's my code that adds the 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:
<com.foo.bar.ConversationLayout
android:id="@+id/loConvo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Any help is appreciated.
Thanks!
Upvotes: 1
Views: 187
Reputation: 51571
From what I can see is that you are not setting any IDs
for the TextViews
you are adding. So, when you call:
params.addRule(BELOW, getChildAt(getChildCount() - 1).getId());
getId()
returns 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
.
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.
Upvotes: 1