在相对布局中动态添加组件

时间:2013-05-27 15:21:36

标签: java android android-layout

我有一个xml结构,如

<TextView
    android:id="@+id/txt1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="26dp"
    android:minWidth="20dp"
    android:text="05"
    android:background="@drawable/rounded_corners"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/txt2"
    style="android:textViewStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="false"
    android:layout_alignParentTop="true"
    android:layout_marginTop="26dp"
    android:layout_toRightOf="@+id/txt1"
    android:background="@drawable/rounded_corners"
    android:minWidth="20dp"
    android:text=""
    android:paddingLeft="5dp"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/txt3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="false"
    android:layout_alignParentTop="true"
    android:layout_marginTop="26dp"
    android:layout_toRightOf="@+id/txt2"
    android:background="@drawable/rounded_corners"
    android:minWidth="20dp"
    android:text=""
    android:paddingLeft="5dp"
    android:textAppearance="?android:attr/textAppearanceMedium" />
...

因为我需要将此TextView动态添加到View。我试图在onCreate()方法中转换相同的,如下所示,

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Drawable rounded_corners = getResources().getDrawable(R.drawable.rounded_corners);

    RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.mainrelativeactivity);

    TextView tv = new TextView(this);
    RelativeLayout.LayoutParams rel = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
    tv.setLayoutParams(rel);
    tv.setText("ABC");
    tv.setBackground(rounded_corners);
    relativeLayout.addView(tv);

    tv = new TextView(this);
    rel = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
    tv.setLayoutParams(rel);
    tv.setText("DEF");
    tv.setBackground(rounded_corners);
    relativeLayout.addView(tv);

}

但我不明白如何设置layout_alignParentLeftlayout_marginTop,最关注的是layout_toRightOf部分?

如果有人帮我指导这样的例子那么它会很棒......

1 个答案:

答案 0 :(得分:0)

您必须使用RelativeLayout.LayoutParams添加规则才能完成您想要的内容..

像这样的东西

用于将视图与另一个视图的右侧对齐

rel.addRule(RelativeLayout.RIGHT_OF, tv.getId());

用于将视图对齐父视图中的左侧

rel.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

给予边距

rel.setMargins(50, 10, 0, 0);