Reputation: 13199
I am trying to make a View
as a divider on my application to separate two elements (two Buttons, two TextViews or whatever) and I would like to have a padding on the left and on the right of that View
(to move the background some space on the left and on the right).
It allows you to set a padding but the View
still continues occupying the full width screen. Here is the code I have:
<View
android:layout_width="wrap_content"
android:layout_height="0.5dp"
android:background="#FFFFFF"
android:paddingLeft="10dp"
android:paddingRight="10dp"/>
How can I set a space on the left and on the right of that View
so the divider will be smaller than screen?
Thanks in advance!
Upvotes: 1
Views: 118
Reputation: 6884
Padding takes care of the inner space. Therefore you would use padding to increase the space between the outline of the view and the elements inside it, whether they are buttons, textviews etc.
Margin takes care of the outer space. You would use this to increase the space between the outline of the view and the element which contains it. Hence what you need. To implement this in a view use the following:
private void setMargins (View view, int left, int top, int right, int bottom) {
if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
p.setMargins(left, top, right, bottom);
view.requestLayout();
}
}
Hope this helps :)
Upvotes: 1
Reputation: 2141
use margins instead of padding
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
Upvotes: 2
Reputation: 13199
Finally I got it. As on Android documentation
it says: Even though a view can define a padding, it does not provide any support for margins, I am not able to use marginLeft
or marginRight
properties.
If you try to set directly android:marginLeft="10dp"
you will get the following error:
No resource identifier found for attribute 'marginLeft' in package 'android'
Nevertheless, you can use android:layout_marginLeft="10dp"
and android:layout_marginRight="10dp"
to get the desired result.
The final View
xml will be like this:
<View
android:layout_width="wrap_content"
android:layout_height="0.5dp"
android:background="#FFFFFF"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"/>
Upvotes: 1