Bae
Bae

Reputation: 912

setBackgroundColor(int color) and RelativeLayout

When i used this XML file...

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"

tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"        
    android:text="@string/hello_world" />

</RelativeLayout>

..I see that background color wrap content

http://img716.imageshack.us/img716/8225/rlayout.jpg

But if i write this RelativeLayout by code...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    RelativeLayout layout = new RelativeLayout(this);

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);


    layout.setBackgroundColor(Color.parseColor("#FF0000"));

    TextView text = new TextView(this);
    text.setText("Hello world");

    //Añado texto
    layout.addView(text);

    layout.setLayoutParams(params);

    setContentView(layout); 
}

...I see that background color match parent instead of wrap content

http://img404.imageshack.us/img404/1427/rlayoutfull.jpg

Any ideas?

Thanks!

Upvotes: 2

Views: 15864

Answers (1)

Emil Adz
Emil Adz

Reputation: 41099

you are never setting the layout params:

layout.setLayoutParams(params);

and I think that you should place the:

TextView text = new TextView(this);
text.setText("Hello world");

and all other view you will add to your layout before you setting the layout params, otherwise there will be no content to wrap-around.

Edit:

what happens when you set:

tried to replace between the two:

 RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
       RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

?

Upvotes: 2

Related Questions