views:

2743

answers:

3

I'm trying to achive the following programmatically (rather than declaratively via XML):

<RelativeLayout...>
   <TextView ...
      android:id="@+id/label1" />
   <TextView ...
      android:id="@+id/label2"
      android:layout_below: "@id/label1" />
</RelativeLayout>

In other words, how do I make the second TextView appear below the first one, but I want to do it in code:

RelativeLayout layout = new RelativeLayout(this);
TextView label1 = new TextView(this);
TextView label2 = new TextView(this);
...
layout.addView(label1);
layout.addView(label2);
setContentView(layout);

Thanks,

Dan

+1  A: 

From what I've been able to piece together, you have to add the view using LayoutParams.

LinearLayout linearLayout = new LinearLayout(this);

RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layout.addRule(RelativeLayout.ALIGN_WITH_PARENT_TOP);

parentView.addView(linearLayout, relativeParams);
TreeUK
+1  A: 

Thanks, TreeUK. I understand the general direction, but it still doesn't work - "B" overlaps "A". What am I doing wrong?

RelativeLayout layout = new RelativeLayout(this);
TextView tv1 = new TextView(this);
tv1.setText("A");

TextView tv2 = new TextView(this);
tv2.setText("B");
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT);
lp.addRule(RelativeLayout.RIGHT_OF, tv1.getId());

layout.addView(tv1);        
layout.addView(tv2, lp);
Dan
In your code sample, you're not actually adding the rule of RelativeLayout.BELOW, tv1.getId();
TreeUK
you need to provide id's to your child views: tv1.setId(1); tv2.setId(2); Parent views do not automatically assign child views an Id, and the default value for an Id is NO_ID. Id's don't have to be unique in a view hiearchy - so 1, 2, 3, etc are all fine values to use - and you must use them for relative anchoring to work in RelativeLayout.
sechastain
A: 

call tv1.setId(1) after tv1.setText("A");