In Android you can set a Background via xml and anything is fine. In some special cases I have the need to set it inside Java (i.e. altering List-Rows). One could think that he can just declare:
View v = findViewById(R.id.some_view);
v.setBackgroundResource(R.drawable.somedrawable);
but unfortunatly this particular View is loosing its padding. I have a facility method like this, that works just fine:
private void applyDifferentBackgroundResource(int resId, View v){
final int paddingBottom = v.getPaddingBottom();
final int paddingLeft = v.getPaddingLeft();
final int paddingRight = v.getPaddingRight();
final int paddingTop = v.getPaddingTop();
v.setBackgroundResource(resId);
v.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
}
But just out of curiosity: Is there a reason, why a View is loosing its padding, or the Android code of setBackgroundResource
can't (or shouldn't) handle the padding itself?