I have this issue on my EditText
and Button
views, where I have a nice padding for them to space away from the text, but when I change the backgrou
I use this pretty easy workaround I define a accentColor
in my style.xml
like below
<item name="colorAccent">#0288D1</item>
and then I use the either of following styles in my Button
tags
style="@style/Base.Widget.AppCompat.Button.Colored"
style="@style/Base.Widget.AppCompat.Button.Small"
for Example :
<Button
android:id="@+id/btnLink"
style="@style/Base.Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tvDescription"
android:textColor="@color/textColorPrimary"
android:text="Visit Website" />
<Button
android:id="@+id/btnSave"
style="@style/Base.Widget.AppCompat.Button.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tvDescription"
android:layout_toRightOf="@id/btnLink"
android:textColor="@color/textColorPrimaryInverse"
android:text="Save" />
Haven't tested this super thoroughly, but this method might be of use:
/**
* Sets the background for a view while preserving its current padding. If the background drawable
* has its own padding, that padding will be added to the current padding.
*
* @param view View to receive the new background.
* @param backgroundDrawable Drawable to set as new background.
*/
public static void setBackgroundAndKeepPadding(View view, Drawable backgroundDrawable) {
Rect drawablePadding = new Rect();
backgroundDrawable.getPadding(drawablePadding);
int top = view.getPaddingTop() + drawablePadding.top;
int left = view.getPaddingLeft() + drawablePadding.left;
int right = view.getPaddingRight() + drawablePadding.right;
int bottom = view.getPaddingBottom() + drawablePadding.bottom;
view.setBackgroundDrawable(backgroundDrawable);
view.setPadding(left, top, right, bottom);
}
Use this instead of view.setBackgroundDrawable(Drawable).
For common searcher,
just add setPadding after setBackgroudDrawable. When you change your drawable, you have to call setPadding again.
Like:
view.setBackgroundDrawable(backgroundDrawable);
view.setPadding(x, x, x, x);
The cleanest way is define your paddings inside a xml-drawable which points to the drawable-image-file
Greatings
Just to explain what's happening :
It's actually a feature. Layout drawables you might use as backgrounds can define a padding this way :
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingRight="8dp"
>
...
</layer-list>
This padding will be set along with the new drawable background. When there's no padding, the default value is 0.
More info from an email written by Romain Guy: https://www.mail-archive.com/android-developers@googlegroups.com/msg09595.html