Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically adding items to a relative layout

I have been searching everywhere for an answer to this question. I'm new to Android and attempting to add items to a relative layout programmatically through java instead of xml. I have created a test class to try it out but the items keep stacking instead of formatting correctly. I simply want one TextView under the other for now (eventually I will use the left of and right of parameters but I am starting simple. What am I missing?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ScrollView sv = new ScrollView(this);
    RelativeLayout ll = new RelativeLayout(this);
    ll.setId(99);
    sv.addView(ll);
    TextView tv = new TextView(this);
    tv.setText("txt1");
    tv.setId(1);
    TextView tv2 = new TextView(this);
    tv2.setText("txt2");
    tv2.setId(2);
    RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    lay.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    ll.addView(tv, lay);
    RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId());
    ll.addView(tv2, p);  this.setContentView(sv);};
like image 648
user597436 Avatar asked Jan 31 '11 20:01

user597436


People also ask

Which type of layout allows the components in relative?

Android RelativeLayout enables you to specify how child views are positioned relative to each other. The position of each view can be specified as relative to sibling elements or relative to the parent.

Which layout allows us to display items on the screen relative to each other?

RelativeLayout : is a ViewGroup that displays child views in relative positions.


2 Answers

    p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId());

This line means that the the bottom of tv2 is aligned with the bottom of tv- in other words, they will cover each other up. The property you want is presumably RelativeLayout.BELOW . However, I strongly recommend using xml for this instead.

like image 115
Jems Avatar answered Oct 12 '22 18:10

Jems


Use:

p.addRule(RelativeLayout.BELOW, tv.getId());
like image 29
Cristian Avatar answered Oct 12 '22 18:10

Cristian