MosesA
MosesA

Reputation: 965

Android - RelativeLayout programmatically

I'm trying to create a layout pro-grammatically but it's not working. Here is the XML version, which looks right.

<?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" />

Which looks like this:

enter image description here

This is the Java version:

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

This is the output:

enter image description here

What am I doing wrong? Thanks.

Upvotes: 0

Views: 875

Answers (2)

stkent
stkent

Reputation: 20128

You haven't set an id on the checkbox, so cbox.getId() is probably not returning anything sensible. See the documentation for setId here.

At any rate, consider using a CheckedTextView instead! Think you might need to specify a drawable to use explicitly, however.

Upvotes: 2

Finkes
Finkes

Reputation: 516

In your Java Version you are using EditText instead oft a TextView like you did in xml

Upvotes: -1

Related Questions