28

I am using a Button created using following code

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

Button btn = new Button(this);
btn.setOnClickListener(newtodobtn);
btn.setText("New Todo");

btn.setBackgroundDrawable(new Button(this).getBackground());

ll.addView(btn);

I have an image in path @drawable/new_todo_image to set as background for the button. How to set it to the Button programmatically?

Niranj Patel
  • 32,980
  • 10
  • 97
  • 133
Pattabi Raman
  • 5,814
  • 10
  • 39
  • 60

6 Answers6

96

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

btn.setBackgroundResource(R.drawable.new_todo_image);
Niranj Patel
  • 32,980
  • 10
  • 97
  • 133
7

Try this:

btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Bandzio
  • 617
  • 2
  • 10
  • 21
1

Try like this

final int 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));
       }
King of Masses
  • 18,405
  • 4
  • 60
  • 77
1

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);
Subhash Khimani
  • 427
  • 7
  • 22
1

try this:

btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
Vineet Shukla
  • 23,865
  • 10
  • 55
  • 63
0

You should put your png files into Drawable folder, then try these codes:

Button buttonSES = (Button) findViewById(R.id.buttonSES)    
buttonSES.setBackgroundResource(R.drawable.image1);  //image1.png 
Bay
  • 467
  • 7
  • 22