0

我有一个 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部分?

如果有人能帮助我举出这样的例子,那就太好了……

4

1 回答 1

0

你必须添加规则RelativeLayout.LayoutParams来完成你想要的..

像这样的东西

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

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

用于在父级中将视图向左对齐

rel.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

给予利润

rel.setMargins(50, 10, 0, 0);
于 2013-05-27T15:30:19.717 回答