Skip to content Skip to sidebar Skip to footer

How To Set The Button Background Image Through Code

I am using a Button created using following code LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); Button btn = new Button(this); btn.setOnClickL

Solution 1:

for set background image for button which is in drawable folder then use below code

btn.setBackgroundResource(R.drawable.new_todo_image);

Solution 2:

Try this:

btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));

Solution 3:

try this:

btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));

Solution 4:

Try like this

finalint sdk = android.os.Build.VERSION.SDK_INT;
    if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN)
     {
      mBtn.setBackgroundDrawable( getResources().getDrawable(R.drawable.new_todo_image) );
     } 
    else
       {
       mBtn.setBackground( getResources().getDrawable(R.drawable.new_todo_image));
       }

Solution 5:

In android studio to set Button background Image write following code :

int image_resid = getApplicationContext().getResources().getIdentifier("image_name", "drawable", getApplicationContext().getPackageName());
button.setBackgroundResource(image_resid);

Post a Comment for "How To Set The Button Background Image Through Code"