Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Created April 17, 2016 14:54
Show Gist options
  • Save vxhviet/f10fd7a027840cb348d925e5650f8f50 to your computer and use it in GitHub Desktop.
Save vxhviet/f10fd7a027840cb348d925e5650f8f50 to your computer and use it in GitHub Desktop.
Define View width by percentage

Source: StackOverflow

Question: How to define Views width by percentage?

Answer:

You are looking for the android:layout_weight attribute. It will allow you to use percentages to define your layout.

In the following example, the left button uses 70% of the space, and the right button 30%.

<LinearLayout
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:text="left" 
        android:layout_width="0dp" 
        android:layout_height="wrap_content" 
        android:layout_weight=".70" /> 

    <Button
        android:text="right" 
        android:layout_width="0dp" 
        android:layout_height="wrap_content" 
        android:layout_weight=".30" />

</LinearLayout>

It works the same with any kind of View, you can replace the buttons with some EditText to fit your needs.

Be sure to set the layout_width to 0dp or your views may not be scaled properly.

Note that the weight sum doesn't have to equal 1, I just find it easier to read like this. You can set the first weight to 7 and the second to 3 and it will give the same result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment