若在xml中有其他的layout 属性,会导致在代码中setBackground与android:background不一致的现象:
例如:
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="12dp"
android:paddingBottom="4dp"
android:id="@+id/background"
android:background="@drawable/card_article_top"
>
若在代码中设置背景,则忽略了padding的效果,导致内容"放大"了,解决办法为:
public void setBackGround(int resourceId) {
int bottom = mBackground.getPaddingBottom();
int top = mBackground.getPaddingTop();
int right = mBackground.getPaddingRight();
int left = mBackground.getPaddingLeft();
mBackground.setBackgroundResource(resourceId);
mBackground.setPadding(left, top, right, bottom);
}
需要注意的是,需要先setBackground后,setPadding,否则无效~
其他属性类似~
本文探讨了在XML布局文件中使用android:background属性时遇到的问题,特别是当与代码中调用setBackground结合使用时,如何正确处理padding以避免内容显示异常。文章提供了具体的解决方案并强调了设置顺序的重要性。

3252

被折叠的 条评论
为什么被折叠?



