我正在尝试以编程方式创建布局,但无法正常工作。
这是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()可能未返回任何明智的信息。请参见the documentation for setId here

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

07-26 05:59