如何在 Android 中以编程方式设置背景可绘制
RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
这是最好的方法吗?
layout.setBackgroundResource(R.drawable.ready);
是正确的.
实现它的另一种方法是使用以下内容:
layout.setBackgroundResource(R.drawable.ready);
is correct.
Another way to achieve it is to use the following:
final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready) );
} else {
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
}
但我认为出现问题是因为您正在尝试加载大图像.
这里 是如何加载大位图的好教程.
But I think the problem occur because you are trying to load big images.
Here is a good tutorial how to load large bitmaps.
更新:
getDrawable(int ) 在 API 级别 22 中已弃用 getDrawable(int )
现在已在 API 级别 22 中弃用.您应该改用支持库中的以下代码:
UPDATE:
getDrawable(int ) deprecated in API level 22 getDrawable(int )
is now deprecated in API level 22.
You should use the following code from the support library instead:
ContextCompat.getDrawable(context, R.drawable.ready)
如果参考ContextCompat.getDrawable,它给你这样的东西:
If you refer to the source code of ContextCompat.getDrawable, it gives you something like this:
/**
* Return a drawable object associated with a particular resource ID.
* <p>
* Starting in {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the returned
* drawable will be styled for the specified Context's theme.
*
* @param id The desired resource identifier, as generated by the aapt tool.
* This integer encodes the package, type, and resource entry.
* The value 0 is an invalid identifier.
* @return Drawable An object that can be used to draw this resource.
*/
public static final Drawable getDrawable(Context context, int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= 21) {
return ContextCompatApi21.getDrawable(context, id);
} else {
return context.getResources().getDrawable(id);
}
}
有关ContextCompat的更多详细信息
More details on ContextCompat
从 API 22 开始,您应该使用 getDrawable(int, Theme)
方法而不是 getDrawable(int).
As of API 22, you should use the getDrawable(int, Theme)
method instead of getDrawable(int).
更新:
如果您使用的是 support v4 库,以下内容对于所有版本就足够了.
UPDATE:
If you are using the support v4 library, the following will be enough for all versions.
ContextCompat.getDrawable(context, R.drawable.ready)
您需要在您的应用 build.gradle 中添加以下内容
You will need to add the following in your app build.gradle
compile 'com.android.support:support-v4:23.0.0' # or any version above
或者在任何 API 中使用 ResourceCompat,如下所示:
Or using ResourceCompat, in any API like below:
import android.support.v4.content.res.ResourcesCompat;
ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null);