Java 如何通过代码设置按钮背景图像
我正在使用使用以下代码创建的Java 如何通过代码设置按钮背景图像,java,android,button,Java,Android,Button,我正在使用使用以下代码创建的按钮 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).getBackgroun
按钮
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\u todo\u image
中有一个图像设置为按钮的背景。如何以编程方式将其设置为按钮?尝试以下操作:
btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
对于可绘图文件夹中的按钮设置背景图像,请使用以下代码
btn.setBackgroundResource(R.drawable.new_todo_image);
试试这个:
btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.new_todo_image));
像这样试试
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));
}
final int sdk=android.os.Build.VERSION.sdk\u int;
if(sdk
在android studio中,要设置按钮背景图像,请编写以下代码:
int image_resid = getApplicationContext().getResources().getIdentifier("image_name", "drawable", getApplicationContext().getPackageName());
button.setBackgroundResource(image_resid);
您应该将png文件放入Drawable文件夹,然后尝试以下代码:
Button buttonSES = (Button) findViewById(R.id.buttonSES)
buttonSES.setBackgroundResource(R.drawable.image1); //image1.png
我得到以下错误:类型视图中的方法setBackgroundDrawable(Drawable)不适用于参数(int)btn.setBackgroundResource(R.Drawable.new_todo_image);此代码符合要求。感谢您提供更好的建议btn.setBackgroundResource(R.drawable.new_todo_image);截至2014年,这已被弃用。