0

我有一个RelativeLayout 的问题。我尝试使用 Java 代码创建以下内容:

<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<CheckBox
    android:id="@+id/CheckBox01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:clickable="false" />

<TextView
    android:id="@+id/TextView03"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:text="TEXT here"
    android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>

上面的 XML 创建了我想要的外观。现在我正在尝试使用 Java 代码来做到这一点:

// First Child: TextView
text = new TextView(context);
text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
text.setText(contentText);
text.setTextSize(20);

// Layout-Info for text
RelativeLayout.LayoutParams text_relativeParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
text_relativeParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
text_relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

// Add text to layout:
this.addView(text, text_relativeParams);
// Checkbox
checkbox = new CheckBox(context);
checkbox.setClickable(false);
checkbox.setChecked(reachable);
checkbox.setBackgroundColor(Color.BLUE);
checkbox.setText("");
checkbox.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

// Layout-Info for Checkbox
RelativeLayout.LayoutParams checkbox_relativeParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
checkbox_relativeParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
checkbox_relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);

// Adding Checkbox to layout:
this.addView(checkbox);

上面的 Java 代码应该和 XML 一样。但是应该和做之间有一点区别。复选框出现在左侧。如何将复选框向右移动?(这是RelativeLayout的派生类,代码在Constructor中)

提前致谢。

4

1 回答 1

0

去掉这行代码

checkbox.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

使用 checkbox_relativeParams 设置复选框的布局参数

RelativeLayout.LayoutParams checkbox_relativeParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
checkbox_relativeParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
checkbox_relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
this.addView(checkbox, checkbox_relativeParams);
于 2012-05-13T19:10:53.263 回答