【问题标题】:Android: Add Checkbox to the right of RelativeLayoutAndroid:在RelativeLayout右侧添加复选框
【发布时间】:2012-05-14 03:10:53
【问题描述】:

我有一个相对布局的问题。我尝试使用 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的派生类,代码在Constructor中)

提前致谢。

【问题讨论】:

    标签: android android-layout checkbox android-relativelayout


    【解决方案1】:

    去掉这行代码

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

    【讨论】:

      猜你喜欢
      • 2014-02-06
      • 2011-03-10
      • 1970-01-01
      • 2014-04-14
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多