设置背景信息:

RelativeLayout layout = (RelativeLayout) findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);

这是最好的方法吗?


当前回答

你也可以设置任何图片的背景:

View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);

其他回答

使用butterknife将可绘制资源绑定到变量,方法是将其添加到类的顶部(在任何方法之前)。

@Bind(R.id.some_layout)
RelativeLayout layout;
@BindDrawable(R.drawable.some_drawable)
Drawable background;

然后在其中一个方法中添加

layout.setBackground(background);

这就是你所需要的

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
     layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ready));
else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
     layout.setBackground(getResources().getDrawable(R.drawable.ready));
else
     layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));

我正在使用minSdkVersion 16和targetSdkVersion 23。 以下是为我工作,它使用

ContextCompat.getDrawable(context, R.drawable.drawable);

而不是使用:

layout.setBackgroundResource(R.drawable.ready);

而使用:

layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));

getActivity()在片段中使用,如果从活动调用则使用此方法。

试试这个。

 int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
 preview = (ImageView) findViewById(R.id.preview);
 preview.setBackgroundResource(res);

你也可以设置任何图片的背景:

View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);