Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does changing the background also change the padding of a LinearLayout?

I have the following LinearLayout. What I don't understand is if I set the background to another image, the padding information are reset. Is there a way to prevent this?

<LinearLayout android:id="@+id/aPanel"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:background="@drawable/bkground"
    android:paddingLeft="15dp" android:paddingRight="15dp"> 

     <!-- some children here -->
     </LinearLayout>

I see the position of the children get shifted when I change the background drawable of the LinearLayout aPanel.

like image 364
michael Avatar asked Sep 11 '25 10:09

michael


2 Answers

This is the default behavior when changing the background Drawable on a View. According to Romain Guy, one of the Android developers, "The reason why setting an image resets the padding is because 9-patch images can encode padding." See his full answer in a similar question.

The fix is to reset the padding in code each time you change the background drawable.

like image 177
happydude Avatar answered Sep 13 '25 01:09

happydude


This is a similar question.

in short, the answer would be :

public static void setViewBackgroundWithoutResettingPadding(final View v, final int backgroundResId) {
    final int paddingBottom = v.getPaddingBottom(), paddingLeft = v.getPaddingLeft();
    final int paddingRight = v.getPaddingRight(), paddingTop = v.getPaddingTop();
    v.setBackgroundResource(backgroundResId);
    v.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
}

The reason for the padding being reset is because the drawable might be a 9-patch drawable .

like image 42
android developer Avatar answered Sep 13 '25 01:09

android developer