4

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?

Rafael T
  • 15,401
  • 15
  • 83
  • 144
  • 2
    Are you using a 9-patch by any chance? – dumamilk Feb 08 '13 at 18:14
  • 1
    Yeah, 9-patches have their own padding -- if you're using them, you'll need to save and restore the padding as you've shown you've done. Me and some friends had a long conversation a while back, but I can't remember the answer now of which takes priority: the 9-patch padding or the padding attributes. Either way, changing the background as in your second method is the best way, if the padding should stay the same in both background images. – Kevin Coppock Feb 08 '13 at 18:27
  • no, its a drawable declared via xml. No 9-patch involved – Rafael T Feb 09 '13 at 01:19
  • You loose the padding on background change, ref. - http://stackoverflow.com/a/10469121/3374428 – Joaquim Ley Sep 28 '14 at 20:40

0 Answers0