androidbuttonbackgroundlayerdrawable

Android button.setBackground


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?


Solution

  • 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);
    }