Steven Akerfeldt
Steven Akerfeldt

Reputation: 629

Making UI elements relative to screen size?

Lets say I wanted to make a relative view with two columns of buttons, left and right.

Where each button takes up exactly 20% of the screen, separated by 10%, with the remaining border on the sides. But to do this for any screen size. DP I think won't work because how do you know the DP pixel count on each different screen?

Basically how do you keep UI's relatively the same and fitting between all devices?

Upvotes: 2

Views: 2011

Answers (1)

anthropomo
anthropomo

Reputation: 4120

Short answer: LinearLayout.

Long answer is here:

Defining a percentage width for a LinearLayout?

There are also ways of getting density at runtime, but the above is easier in the long run.

Get ready for some pseudo-xml!

<LinearLayout double fill parent, vertical>
    <RelativeLayout w = 0, h = 0, weight smallish>
         <Button A />
    </RelativeLayout>
    <LinearLayout w = 0, h = 0, weight largish. horizontal>
         <!-- maybe you want these to be RelativeLayout and set the buttons
         as centerHorizontalInParent="true" -->
         <LinearLayout w = 0, h = 0, weight whatever 20% is>
              <Buttons with some padding/margins>
         </LinearLayout>
         <Some kind of spacer, or just pad the LLs />
         <LinearLayout repeat above />
     </LL>
</LL>

Edit:

If you are bent on doing alot of dynamic resizing, I have this custom class for getting screen size:

public class ScreenGetter {
    private float pixHeight;
    private float pixWidth;
    private float dpHeight;
    private float dpWidth;
    private float density;

public ScreenGetter (Context context){
    Display display = ((WindowManager)
                context.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics ();
    display.getMetrics(metrics);

    pixHeight = metrics.heightPixels;
    pixWidth = metrics.widthPixels;
    density  = context.getResources().getDisplayMetrics().density;
    dpHeight = pixHeight / density;
    dpWidth  = pixWidth / density;
}

public float getPixHeight(){return pixHeight;}
public float getPixWidth(){return pixWidth;}
public float getDpHeight(){return dpHeight;}
public float getDpWidth(){return dpWidth;}
public float getDensity(){return density;}

}

Obviously you'll need to do some math to figure out what you want at different sizes and densities. You also need to account for parts of the screen you are not using (ActionBar, etc.)

Upvotes: 1

Related Questions