Android:在RelativeLayout右侧添加复选框

时间:2012-05-13 18:51:12

标签: android android-layout checkbox relativelayout

我遇到了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-Code:

// 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的派生类,代码在构造函数中)

提前致谢。

1 个答案:

答案 0 :(得分: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);