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

353

设置背景:

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

这是最好的方法吗?


3
谢谢!您的问题和所有有用的回答帮助我设置了一个小部件内图像按钮的背景资源。以下是示例代码,如果有人感兴趣:remoteViews.setInt(R.id.btn_start,"setBackgroundResource", R.drawable.ic_button_start); - Sam
1
Kotlin解决方案,适用于可能需要的人:https://dev59.com/GFPTa4cB1Zd3GeqPkpzv#54495750 - Hamed Jaliliani
14个回答

596

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)。

更新:
如果您正在使用支持v4库,则以下内容将足以适用于所有版本。

ContextCompat.getDrawable(context, R.drawable.ready)
您需要在您的应用程序 build.gradle 中添加以下内容。
compile 'com.android.support:support-v4:23.0.0' # or any version above

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

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

4
“getDrawable(int)”已经过时。 - S.M_Emamian
嘿,我想在图像按钮的背景图片是特定的可绘制资源时才执行任务。我该怎么比较?我已经尝试过if(buttonBackground.equals(R.drawable.myDrawable)),其中Drawable buttonBackground = myButton.getBackground();但是我收到了这个错误:http://snag.gy/weYgA.jpg - Ruchir Baronia
对于最新版本的方法,您还需要使用myActivity.getTheme(),而不是空参数:myView.setBackground(getResources().getDrawable(R.drawable.my_background, activity.getTheme())); - Zon
或者你可以使用 AppCompatResources.getDrawable(this.getContext(), resId),Google 已经在 AppCompat* 控件/视图中实现了它,例如:android.support.v7.widget.AppCompatCheckBox - mochadwi

119
尝试这个:
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));

对于API 16及以下版本:

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

2
但这是同样的事情,Ahmad :) - Mohammad Ersan
4
好的,那我会参考懒惰忍者的回答。 - Ahmad
43
不需要使用getResources().getDrawable()。正确的代码是 layout.setBackgroundResource(R.drawable.ready);,就像原帖中所使用的一样。这里的问题来自于位图的大小。 - BVB
1
setBackground仅适用于API级别16或更高。 - Erwan

20
RelativeLayout relativeLayout;  //declare this globally

现在,像onCreate、onResume这样的任何函数内部

relativeLayout = new RelativeLayout(this);  
relativeLayout.setBackgroundResource(R.drawable.view); //or whatever your image is
setContentView(relativeLayout); //you might be forgetting this

12

我正在使用minSdkVersion 16和targetSdkVersion 23。
以下内容适用于我,它使用了

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

使用以下方式代替:

layout.setBackgroundResource(R.drawable.ready);

最好使用:

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

getActivity() 用于片段中,如果从活动中调用,请使用 this


10

如果您使用 AndroidX,应使用:

AppCompatResources.getDrawable(context, R.drawable.your_drawable)

之前列出的方法已过时。


9
您可以设置任何图像的背景:
View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);

这解决了我的问题,但我需要在代码中实现 (.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) - Armando Marques da S Sobrinho
1
现在已经弃用了。 - Roman Soviak

3
setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));

2
请解释一下广告。 - vonbrand

2
如果您的背景图像目前在drawable文件夹中,尝试将图像从drawable移动到项目中的drawable-nodpi文件夹。这对我有用,似乎否则图像会自行重新缩放。

5
如果您没有高清质量的项目所需图像的副本,为什么要让Android使用普通的drawable文件夹将它们缩放到糟糕的质量。即使这个问题已经很老了,如果它仍然在谷歌上出现,那么在其中发布新内容是可以的。 - Jordy

1

使用butterknife将可绘制资源绑定到变量,通过在类的顶部添加以下内容(在任何方法之前)。

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

然后在你的方法之一中添加。
layout.setBackground(background);

那就是你所需要的全部


1

尝试使用 ViewCompat.setBackground(yourView, drawableBackground) 方法


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接