Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何通过代码设置按钮背景图像_Java_Android_Button - Fatal编程技术网

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年,这已被弃用。