Android - 编程方式的 RelativeLayout

Android - RelativeLayout programmatically

我正在尝试以编程方式创建布局,但它不起作用。 这是 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);

这是输出:

我做错了什么?谢谢。

在您的 Java 版本中,您使用的是 EditText 而不是像 xml

中那样使用 TextView

您尚未在复选框上设置 ID,因此 cbox.getId() 可能不会返回任何有意义的信息。参见 the documentation for setId here

无论如何,请考虑改用 CheckedTextView!但是,您认为您可能需要明确指定要使用的可绘制对象。