user1788048
user1788048

Reputation: 265

android:layout_width along with layout weight usage

why should i put android:layout_width="0px" when i use android:layout_weight property? For example following is my main.xml file , and in that i used android:layout_width="wrap_content", and everything works fine, so why android:layout_width="0px" should be used when i am using the layout_weight property?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="horizontal">
<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText" android:hint="enter your name"
        android:layout_weight="3"/>
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"
        android:id="@+id/button"
        android:layout_weight="0"/>
</LinearLayout>

and this is how my layout looks: enter image description here

Upvotes: 2

Views: 1776

Answers (3)

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52936

You certainly don't have to. Additionally weight=0 doesn't make much sense. The weight parameter controls what part of the remaining space in the layout the widget occupies. So setting width=0 effectively tells it to take up only the remaining space. If you set width=30, it will occupy 30 px|dp + all the remaining space. Setting 0 as the width makes it easier to get a predictable result on different screen sizes.

A common pattern is to have two widgets with width=0 and equal weight to make them equally sized inside the parent container, where you don't care about the actual size (width or height).

Upvotes: 2

Nirav Ranpara
Nirav Ranpara

Reputation: 13785

layout_weight you can specify a size ratio between multiple views.

E.g. you have a Tabelview and a image which should show some additional information to the layout. The tabel should use 3/4 of the screen and image should use 1/4 of the screen. Then you will set the layout_weight of the tabelview to 3 and the layout_weight of the image to 1.

To get it work you also have to set the height or widthto 0px.

http://developer.android.com/guide/topics/ui/declaring-layout.html#CommonLayouts

Upvotes: 1

MysticMagicϡ
MysticMagicϡ

Reputation: 28823

Layout weight itself is used to give appropriate width as per weight property. Check this

This attribute assigns an "importance" value to a view in terms of how much space is should occupy on the screen. A larger weight value allows it to expand to fill any remaining space in the parent view.

So eclipse suggests to give width as 0px

Upvotes: 1

Related Questions