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?
for set background image for button which is in drawable folder then use below code
btn.setBackgroundResource(R.drawable.new_todo_image);
Try this:
btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
try this:
btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
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));
}
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);
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
精彩评论