0

How can i set layout margin individually in android?
Example case: i want the margin for top:15, right:12, bottom:13, left:16

How to that in android?
I have background as web developer, i though it will the same as css with setup like this margin: 15 12 13 16; but seems it not working with android

<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_margin">15dp 12dp 13dp 16dp</dimen>

</resources>

What is the right way to achieve that? is there any link for documentation to for this?

flx
  • 14,146
  • 11
  • 55
  • 70
GusDeCooL
  • 5,639
  • 17
  • 68
  • 102

2 Answers2

2

Use seperate dimens like this:

<dimen name="activity_margin_left">15dp</dimen>
<dimen name="activity_margin_right">13dp</dimen>
<dimen name="activity_margin_top">12dp</dimen>
<dimen name="activity_margin_bottom">16dp</dimen>

You may need to change the values, I'm not aware of the order of css dimens.

Then apply them to your layout:

<LinearLayout ....
    android:layout_marginLeft="@dimen/activity_margin_left"
    android:layout_marginRight="@dimen/activity_margin_right"
    android:layout_marginTop="@dimen/activity_margin_top"
    android:layout_marginBottim="@dimen/activity_margin_bottom"/>
flx
  • 14,146
  • 11
  • 55
  • 70
  • @fix Thanks, is there any shortcut so i can just use 1 line of code instead of four which it define margin of each? I would like to make my code is short as possible – GusDeCooL Dec 10 '13 at 03:30
  • 2
    @GusDeCooL not unless you want each of the values to be the same, you can't. – panini Dec 10 '13 at 03:31
  • @panini i see. so this is the best that we got for now. hopefully android dev will consider this in the next version @_@ – GusDeCooL Dec 10 '13 at 03:32
  • 1
    You may want to use something like `activity_margin_horizontal` and `activity_margin_vertical`, but anyway: internally the `dimen` translates to a single `float`. There is no way to change that in future versions without breaking it completely for legacy API version. – flx Dec 10 '13 at 03:35
2

You can do it in two ways. First, in layout and you can't set it like CSS. You need to set:

android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:layout_marginRight="15dp"
android:layout_marginBottom="15dp"  

Second, programmatically like below:

// initiate your margins value in dp
(int) (px / getResources().getDisplayMetrics().density);

// and set these value in setMargin method
LayoutParams params = new LayoutParams(
    LayoutParams.WRAP_CONTENT,      
    LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourLayout.setLayoutParams(params);  
Blo
  • 11,903
  • 5
  • 45
  • 99
  • 1
    I think you could read this answer: http://stackoverflow.com/a/3002321/2668136 and this answer will be helpful: http://stackoverflow.com/a/6327095/2668136 / Enjoy. – Blo Dec 10 '13 at 03:43