Android: Center a button or view horizontally but have a margin offset from the top of the layout

For the title screen, I wanted something that used the layout system without hard-coding pixel values.

Ideally, it'd look like this.

image

I needed this to work using the code rather than layout editor, as the editor only allowed me to enter in fixed pixel values for the margin offset.

The red area had to be approximately 45% of the screen, and the rest would be dedicated to the buttons.

The blue areas are just spacing, evenly distributed between the buttons which have a width which is content wrapped.

Using the linear layout, I was able to get this working via the code.

private void addButtons() {
LayoutParams lp; // Instance of LinearLayout.LayoutParams

lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
lp.topMargin = (int) (G.screenH * 0.45);
this.addView(btnPlay, lp); // This uses its own one to be displayed half-screen

lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_HORIZONTAL;
lp.topMargin = 5;
this.addView(btnSettings, lp);
this.addView(btnScores, lp);
this.addView(btnAbout, lp);
this.addView(btnExit, lp);
}

The first button needs its own layout parameter, as it has a different offset to the others. The other buttons are separated by a 5 pixel gap.

It'd be a good idea to make that gap a density independant pixel size by converting it first.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog