以编程方式为TextView设置layout_toLeftOf和layout_below

时间:2013-11-15 16:17:47

标签: android layout textview relativelayout

我正在创建RelativeLayout中包含的任意数量的TextView。如何以编程方式将TextView放在彼此的下方或旁边?

我猜我应该使用* layout_toLeftOf *和* layout_below *,但是如何使用?

我知道我可以使用RelativeLayout.LayoutParams,但这似乎只是定位布局而不是单个TextView。

到目前为止尝试:

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

}

1 个答案:

答案 0 :(得分:4)

您应该在RelativeLayout.LayoutParams上设置新的TextView,而不是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 );
    }

}