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
  • 36,011
  • 11
  • 98
  • 132
Pattabi Raman
  • 5,694
  • 10
  • 37
  • 59

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
  • 36,011
  • 11
  • 98
  • 132
7

Try this:

btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
Alex Lockwood
  • 82,434
  • 38
  • 201
  • 248
Bandzio
  • 607
  • 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
  • 17,833
  • 4
  • 58
  • 76
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
  • 429
  • 7
  • 22
1

try this:

btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
Vineet Shukla
  • 23,785
  • 9
  • 55
  • 64
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
  • 439
  • 6
  • 21