Search code examples
androidlayouttextviewandroid-relativelayout

Programmatically set layout_toLeftOf and layout_below for TextView


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 );
    }
}

Solution

  • 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 );
        }
    
    }