Android-以编程方式设置RelativeLayout

Adegoke A

我正在尝试以编程方式创建布局,但无法正常工作。这是XML版本,看起来不错。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip" 
android:paddingBottom="6dip"
android:layout_width="fill_parent" 
android:layout_height="fill_parent">

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/checkBox1"
    android:layout_alignBottom="@+id/checkBox1"
    android:layout_alignParentRight="true"
    android:layout_toRightOf="@+id/checkBox1"
    android:text="TextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextView" />

看起来像这样:

在此处输入图片说明

这是Java版本:

    RelativeLayout.LayoutParams  lp;

    RelativeLayout rl = new RelativeLayout(this);
    lp = new RelativeLayout.LayoutParams (RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    rl.setLayoutParams(lp);

    CheckBox cbox = new CheckBox(this);
    lp = new RelativeLayout.LayoutParams (RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    lp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
    cbox.setLayoutParams(lp);

    EditText etext = new EditText(this);
    etext.setText("TextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextViewTextView");
    lp = new RelativeLayout.LayoutParams (RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    lp.addRule(RelativeLayout.ALIGN_BASELINE, cbox.getId());
    lp.addRule(RelativeLayout.ALIGN_BOTTOM, cbox.getId());
    lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
    lp.addRule(RelativeLayout.RIGHT_OF, cbox.getId());
    etext.setLayoutParams(lp);

    rl.addView(cbox);
    rl.addView(etext);
    this.setContentView(rl);

这是输出:

在此处输入图片说明

我究竟做错了什么?谢谢。

斯特肯特

您尚未在复选框上设置ID,因此cbox.getId()可能未返回任何明智的信息。请参阅此处的文档setId

无论如何,请考虑改用CheckedTextView认为您可能需要指定一个drawable才能显式使用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章