如何通过代码设置按钮的背景图片

28
我正在使用以下代码创建的一个按钮
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);

我有一张位于路径 @drawable/new_todo_image 的图片,想要将其设置为按钮的背景。如何以编程方式设置它到 Button 上?

6个回答

96

如果要为位于drawable文件夹中的按钮设置背景图像,则使用以下代码

btn.setBackgroundResource(R.drawable.new_todo_image);

7

试试这个:

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

4
截至2014年,此功能已被弃用。 - katzenhut

1
尝试像这样
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));
       }

1
在Android Studio中设置按钮背景图像,请编写以下代码:

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

1

试试这个:

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

我遇到了以下错误: 类型View中的方法setBackgroundDrawable(Drawable)不适用于参数(int)。 - Pattabi Raman
btn.setBackgroundResource(R.drawable.new_todo_image); 这段代码符合要求。感谢您提供更好的建议。 - Pattabi Raman
btn.setBackgroundResource(R.drawable.new_todo_image); - Pattabi Raman

0

你应该将你的png文件放入Drawable文件夹中,然后尝试使用以下代码:

Button buttonSES = (Button) findViewById(R.id.buttonSES)    
buttonSES.setBackgroundResource(R.drawable.image1);  //image1.png 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接