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

て烟熏妆下的殇ゞ 提交于 2019-11-27 20:31:20

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.

android developer

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 .

You can use shape to set the background with single colour or image and apply padding like this:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <corners
        android:bottomLeftRadius="8dip"
        android:topLeftRadius="8dip"/>
    <padding
        android:bottom="0dip"
        android:left="0dip"
        android:right="0dip"
        android:top="0dip"/>
</shape>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!