0

I want to set background for the button. With Android 4.1.2 everything works fine, but if launch with Android 4.0 I've got an error

java.lang.NoSuchMethodError: android.widget.Button.setBackground 

with code

LayerDrawable composite = new LayerDrawable(layers);
button.setBackground(composite);

So how can I set LayerDrawable background but with Android 4.0 or earlier?

  • 2
    http://stackoverflow.com/questions/18559248/button-setbackgrounddrawable-background-throws-nosuchmethoderror – eleven Sep 01 '14 at 18:37
  • create xml layer and set it for your button button.setBackgroundDrawable(getResources().getDrawable(R.drawable.layer)); (setBackground come in api level 16) – MHP Sep 01 '14 at 18:52

3 Answers3

2

While Both of the above answers are close you should really use

Build.VERSION.SDK_INT

as Build.VERSION.SDK returns a string, and has been deprecated since API 4

if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN){
         LayerDrawable composite = new LayerDrawable(layers);
         button.setBackgroundDrawable(composite);
}else{
         LayerDrawable composite = new LayerDrawable(layers);
         button.setBackground(composite);
}
gsueagle2008
  • 4,583
  • 10
  • 36
  • 46
0

Try this...

if(Build.VERSION.SDK < Build.VERSION_CODES.ICE_CREAM_SANDWICH){
     LayerDrawable composite = new LayerDrawable(layers);
     button.setBackgroundDrawable(composite);
}else{
     LayerDrawable composite = new LayerDrawable(layers);
     button.setBackground(composite);
}

setBackground drawable receives as a parameter (Drawable background)...

i hope helpp you...

Javier
  • 23
  • 2
  • 9
0

setBackground method is only available for API level 16 or above. You are probably using the method for API level below 16, that's why it's throwing NoSuchMethodError. You might want to try setBackgroundDrawable for lower API versions. Something like this would do:

if(Build.VERSION.SDK < Build.VERSION_CODES.JELLY_BEAN){
     LayerDrawable composite = new LayerDrawable(layers);
     button.setBackgroundDrawable(composite);
}else{
     LayerDrawable composite = new LayerDrawable(layers);
     button.setBackground(composite);
}
Avi Singh
  • 171
  • 2
  • 7