我想设置一个视图的背景绘图。这有两个方法(据我所知):setBackground和setBackgroundDrawable。

当我使用setBackground时,它说它已添加在API级别16,但我的项目的最小SDK版本是7。我猜在16秒以下就不管用了,对吗?但当我使用setBackgroundDrawable时,它说它已弃用。

我应该用什么?


当前回答

我知道这是一个老问题,但我也有类似的情况,我的解决方案是

button.setBackgroundResource( R.drawable.ic_button );
Drawable d = button.getBackground();

然后你可以使用“绘制”,应用颜色滤镜等等

其他回答

似乎目前这两个函数之间没有区别,如源代码所示(归功于这篇文章):

public void setBackground(Drawable background) {
    //noinspection deprecation
    setBackgroundDrawable(background);
}

@Deprecated
public void setBackgroundDrawable(Drawable background) { ... }

所以这只是一个命名决定,类似于fill-parent vs match-parent。

使用setBackgroundResource (R.drawable.xml / png)

我也有这个问题,但我做了一个工作使用ImageView。

尝试使用RelativeLayout并在其中添加一个ImageView(宽度和高度:fill_parent, scaleType: center)。

同时确保imageview是RelativeLayout中的第一个元素,因此它将作为背景。

使用ViewCompat。setBackground(视图、背景);

它被弃用了,但仍然可以使用,所以你可以使用它。但如果你想完全正确,只是为了它的完整性……你可以这样做:

int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    setBackgroundDrawable();
} else {
    setBackground();
}

为此,你需要将buildTarget api设置为16,并将min build设置为7或类似的东西。