怎么设置背景绘制编程Android中 [英] How set background drawable programmatically in Android

查看:193
本文介绍了怎么设置背景绘制编程Android中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

时做到这一点的最好方法是什么?

Is the best way to do it?

推荐答案

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( getResources().getDrawable(R.drawable.ready) );
} else {
    layout.setBackground( getResources().getDrawable(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)去precated在API级别22


getDrawable(INT)是pcated在API级别22现在去$ P $。 你应该使用下面的code从支持库,而不是:

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)

如果你指的来源$ C ​​$ C <一个href="http://grep$c$c.com/file/repository.grep$c$c.com/java/ext/com.google.android/android/5.0.1_r1/android/support/v4/content/ContextCompat.java#ContextCompat.getDrawable%28android.content.Context%2Cint%29">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);
    }
}

在<一个更多细节href="http://developer.android.com/reference/android/support/v4/content/ContextCompat.html">ContextCompat

由于API 22的,你应该使用 getDrawable(INT,主题)方法,而不是getDrawable(INT)。

As of API 22, you should use the getDrawable(int, Theme) method instead of getDrawable(int).

这篇关于怎么设置背景绘制编程Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆