Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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?

like image 996
Pattabi Raman Avatar asked Sep 13 '11 06:09

Pattabi Raman


People also ask

How do you make a button your background image in HTML?

The default button in HTML can be changed to an image using CSS. The required button is selected using the respective CSS selector. The background property can then be set to include a background image and change the image type as required. The border of the button can also be removed to show only the image itself.


3 Answers

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

btn.setBackgroundResource(R.drawable.new_todo_image); 
like image 71
Niranj Patel Avatar answered Sep 28 '22 03:09

Niranj Patel


Try this:

btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
like image 20
Bandzio Avatar answered Sep 28 '22 03:09

Bandzio


try this:

btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
like image 24
Vineet Shukla Avatar answered Sep 28 '22 02:09

Vineet Shukla