1

I'm creating an arbitrary number of TextViews contained within a RelativeLayout. How do I place the TextViews below or next to each other programmatically?

I'm guessing I should use layout_toLeftOf and layout_below, but how?

I know I can use RelativeLayout.LayoutParams, but that only seems to position the layout and not the individual TextViews.

Attempt so far:

public void updateTS ( ArrayList<String> arrayList ) {
    RelativeLayout rl = ( RelativeLayout ) mView.findViewById ( R.id.overview );
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams ( RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT );

    for ( int i = 0; i < arrayList.size (); i++ ) {
        TextView tv = new TextView ( getActivity () );
        tv.setId ( i );
        tv.setText ( arrayList.get ( i ).toString () );

        if ( i > 0 ) {
            lp.addRule ( RelativeLayout.BELOW, i - 1 );
        }

        rl.addView ( tv );
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
abc32112
  • 2,457
  • 9
  • 37
  • 53

1 Answers1

4

You should set a new RelativeLayout.LayoutParams on the TextView, not the RelativeLayout:

public void updateTS ( ArrayList<String> arrayList ) {
    RelativeLayout rl = ( RelativeLayout ) mView.findViewById ( R.id.overview );

    for ( int i = 0; i < arrayList.size (); i++ ) {
        TextView tv = new TextView ( getActivity () );
        tv.setId ( i );
        tv.setText ( arrayList.get ( i ).toString () );

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams ( RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT );

        if ( i > 0 ) {
            lp.addRule ( RelativeLayout.BELOW, i - 1 );
        }

        tv.setLayoutParams(lp);
        rl.addView ( tv );
    }

}
WonderCsabo
  • 11,947
  • 13
  • 63
  • 105