简体   繁体   中英

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM