如何在 Android 中以编程方式设置背景可绘制对象

新手上路,请多包涵

设置背景:

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

是最好的方法吗?

原文由 Chad Bingham 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 546
2 个回答

layout.setBackgroundResource(R.drawable.ready); 是正确的。

实现它的另一种方法是使用以下内容:

 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));
}

但我认为出现问题是因为您正在尝试加载大图像。

是一个很好的教程如何加载大位图。

更新:

在 API 级别 22 中不推荐使用 getDrawable(int)

getDrawable(int ) 现在在 API 级别 22 中已弃用。您应该改用支持库中的以下代码:

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

如果您参考 ContextCompat.getDrawable 的源代码,它会为您提供如下内容:

 /**
 * 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 的更多详细信息

从 API 22 开始,您应该使用 getDrawable(int, Theme) 方法而不是 getDrawable(int)。

更新:

如果您使用的是 support v4 库,以下内容对于所有版本就足够了。

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

您需要在应用程序 build.gradle 中添加以下内容

compile 'com.android.support:support-v4:23.0.0' # or any version above

或者在任何 API 中使用 ResourceCompat,如下所示:

 import android.support.v4.content.res.ResourcesCompat;
ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null);

原文由 Lazy Ninja 发布,翻译遵循 CC BY-SA 3.0 许可协议

试试这个:

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

对于 API 16<:

 layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));

原文由 Ahmad 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题