Henley Chiu Henley Chiu - 1 month ago 7
Android Question

Android: Setting width percentage of view in RelativeLayout

I'm using a RelativeLayout, and want to center the orange bar below in the center and fill up 90% of the width. I know this is possible to do using a LinearLayout using percentage, but how do I do so with a RelativeLayout?

Do I have to programatically calculate how wide is the screen (in dp), and set this 90% of this as the width of the orange view?

In short, I want something like this, where the orange bar takes up 90% of the screen centered in the middle using a RelativeLayout, without hardcoding x and y coordinates, so that it works on all screen densities. (The dark bars in the edge are the edge of the phone)

enter image description here

Answer

Just a guess, but worth a try :) Please redesign your layout structure like below:

<LinearLayout[with 90% width]>
    <RelativeLayout
           android:layout_width="fill_parent" 
           ...
         <!--this will fill up its parent i.e above LinearLayout which is 90% of the screen width -->
     >
           <!--child views goes here.. -->
     </RelativeLayout>
</LinearLayout>
Comments