2

I would like to layout all my screens on Android so they are compatible with whatever screen size and resolution. So I thought the best would be to use some kind of relative specification using the weight attribute.

I know how to specify a button's width relative to its parents, however I do not have any idea how to apply this to all aspects of the layout. The logic behind it ideally would look like:

horizontalSize = 100%
verticalSize = 100%

Button1:
20% padding to top   <-  no idea, how to do this, (only using fixed sizes in relative layout)
10% height           <-  no idea, how to do this
50% width            <-  with weight attribute
center horizontally  <-  with layout_centerHorizontal

Button2:
20% padding to Button1 <- only know relative with use of fixed pixels
5%  padding to left
30% width
10% height

Button3:
20% padding to Button1
5% padding to right
30% width
10% height

....  

Many thanks!

user387184
  • 10,953
  • 12
  • 77
  • 147

2 Answers2

5

A way (maybe not a good one) to achieve this, is to programmatically build the UI using :

int width, height;
float scale;
private Display mDisplay;
mDisplay = getApplicationContext().getWindow().getWindowManager().getDefaultDisplay(); 
width = mDisplay.getWidth();
height = mDisplay.getHeight();
scale = getApplicationContext().getResources().getDisplayMetrics().density;

With this you can calculate sizes according to you screen (width and height) and scale will help you all the dip/pix convertion :

int dip2pix(int dip)
{
    return Math.round(dip * scale);
}

int pix2dip(int pix)
{
    return Math.round(pix / scale);
}
mthpvg
  • 3,789
  • 3
  • 26
  • 34
3

First of all, you should try to design your layout without absolut pixel values. Instead use dp/dip units (density independent pixels). The basis for all layouts is the medium screensize with 320x480 pixel. So design your layout that it would fit on 320x480 and instead of px use dp units and it will look the same on all screens in the end.

An example for your Button1:

20% of 480 = 96, so your padding top value would be 96dp
10% of 480 = 48dp
50% of 320 = 160dp
banzai86
  • 727
  • 1
  • 5
  • 13
  • I am not sure about the 320x480, I read somewhere else that it also might be 160. See here: http://stackoverflow.com/questions/2025282/difference-of-px-dp-dip-and-sp-in-android – user387184 Oct 04 '11 at 07:30
  • 320x480 is the right size for a normal ratio mdpi phone yes. However these days you need to remember people will frequently be using landscape devices, as well as the fact that there are beginning to be android devices with slightly non standard aspect ratios. 160 is the mdpi dpi, 240 is hdpi, so everything is scaled x1.5 – Zulaxia Oct 04 '11 at 07:36
  • http://developer.android.com/guide/practices/screens_support.html 320x480 = 160dp – banzai86 Oct 04 '11 at 07:40
  • @Zulaxia you are correct, but in most cases you will design a seperate layout for landscape view anyway – banzai86 Oct 04 '11 at 07:51