1

I am adding textview on runtime and I want textview to be added on the last line or next line if it cannot fit on the last line. I am trying to use RelativeLayout . I am trying to specify params like ALIGN_PARENT_LEFT But this is not working. So, I wanted to ask which layout should I use ?

RelativeLayout ll = (RelativeLayout) findViewById(R.id.categorylayout);
    //  ll.setGravity(Gravity.LEFT );
        RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) ll.getLayoutParams();
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);  
        for(int i =0 ; i<tags.size();i++){
            TextView tt = new TextView(this);
            tt.setText(tags.get(i));
            tt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            tt.setBackgroundColor(Color.RED);
            ll.addView(tt  );
        }
Arjit
  • 565
  • 9
  • 27

2 Answers2

2

you are not using params, I believe you intended to use

tt.setLayoutParams(params);

instead of

tt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

However this way TextViews will overlap each other, so you might also want to .addRule() for vertical alignment inside your loop.

edit

for(int i =0 ; i<tags.size();i++){
    TextView tt = new TextView(this);
    tt.setText(tags.get(i));
    tt.setId(i+1);

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); 
    if (i == 0)
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    else 
        params.addRule(RelativeLayout.BELOW, i);

    tt.setLayoutParams(params));
    tt.setBackgroundColor(Color.RED);
    ll.addView(tt);
}

brief exlpanation: you set ids for each TextView (as explained here, RelativeLayout resolves only ids for each children), and so next one will be below previous. First one is aligned with parent's top. I haven't tested it, but at least it is starting point.

Vladimir
  • 9,683
  • 6
  • 36
  • 57
  • Do you mean example for vertical alignment? – Vladimir Oct 27 '11 at 14:50
  • I ment how to add a rule . I think you were telling something like this . Thanks a lot I got it working. http://stackoverflow.com/questions/3885077/relativelayout-programatically-in-android – Arjit Oct 27 '11 at 14:59
0

If you know how many widgets in your xml file,then using LinearLayou**t with **vertical_orientaion you can add it at any specified position like this:

ll.addView(tt,your_position);

Hope this will help. :)

Android Killer
  • 18,174
  • 13
  • 67
  • 90
  • No actually I can add two textView one the same line but if i do with this i cannot add two textview on the same line – Arjit Oct 27 '11 at 14:44