设置背景信息:
RelativeLayout layout = (RelativeLayout) findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
这是最好的方法吗?
设置背景信息:
RelativeLayout layout = (RelativeLayout) findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
这是最好的方法吗?
当前回答
使用butterknife将可绘制资源绑定到变量,方法是将其添加到类的顶部(在任何方法之前)。
@Bind(R.id.some_layout)
RelativeLayout layout;
@BindDrawable(R.drawable.some_drawable)
Drawable background;
然后在其中一个方法中添加
layout.setBackground(background);
这就是你所需要的
其他回答
如果您的背景现在在drawable文件夹中,请尝试将图像从drawable文件夹移动到项目中的drawable-nodpi文件夹。这为我工作,似乎其他图像是由他们自己重新缩放。
如果你使用AndroidX,你应该使用:
AppCompatResources.getDrawable(context, R.drawable.your_drawable)
不推荐使用前面列出的方法。
试试这个:
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
对于API 16<:
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));
试试这个。
int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
preview = (ImageView) findViewById(R.id.preview);
preview.setBackgroundResource(res);
setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));