一、折中办法
1.1 方法一
int bottom = theView.getPaddingBottom();
int top = theView.getPaddingTop();
int right = theView.getPaddingRight();
int left = theView.getPaddingLeft();
theView.setBackgroundResource(R.drawable.entry_bg_with_image);
theView.setPadding(left, top, right, bottom);
int top = theView.getPaddingTop();
int right = theView.getPaddingRight();
int left = theView.getPaddingLeft();
theView.setBackgroundResource(R.drawable.entry_bg_with_image);
theView.setPadding(left, top, right, bottom);
1.2 方法二
int pad = resources.getDimensionPixelSize(R.dimen.linear_layout_padding);
theView.setBackgroundResource(R.drawable.entry_bg_with_image);
theView.setPadding(pad, pad, pad, pad);
theView.setBackgroundResource(R.drawable.entry_bg_with_image);
theView.setPadding(pad, pad, pad, pad);
代码说明:
实际上就是在setBackgroundResource之后重新设置一下padding。
二、原帖网址
http://*.com/questions/5890379/android-setbackgroundresource-discards-my-xml-layout-attributes
三、搜索关键字
GOOGLE:"android setbackgroundresource changes padding"
本文转自博客园农民伯伯的博客,原文链接:[Android疑难杂症]动态改变Background后Padding无效的问题,如需转载请自行联系原博主。