Reputation: 5758
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?
Upvotes: 0
Views: 355
Reputation: 11988
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);
Upvotes: 2
Reputation: 14226
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"/>
Upvotes: 2