来源:小编 更新:2024-10-14 07:27:11
用手机看
Android 动态改变背景与边距的解决方案
在Android开发过程中,我们经常需要根据不同的场景动态改变视图的背景和边距。然而,在实际开发中,我们可能会遇到一些问题,比如在设置背景后边距失效的情况。本文将针对这些问题,提供一些解决方案。

方法一:手动设置padding
通过获取原始的padding值,在设置背景后重新设置padding,可以解决这个问题。
int bottom = theView.getPaddingBottom();
int top = theView.getPaddingTop();
int right = theView.getPaddingRight();
int left = theView.getPaddingLeft();
theView.setBackgroundResource(R.drawable.entrybgwithimage);
theView.setPadding(left, top, right, bottom);
方法二:使用dimen资源
通过使用dimen资源,可以简化padding的设置过程。
int pad = resources.getDimensionPixelSize(R.dimen.linearlayoutpadding);
theView.setBackgroundResource(R.drawable.entrybgwithimage);
theView.setPadding(pad, pad, pad, pad);

方法一:使用selector属性
通过使用selector属性,可以为LinearLayout设置不同的背景,以实现动态改变背景的效果。
<selector xmlns:android=