setBackground vs setBackgroundDrawable (Android)

2019-01-01 04:57发布

I want to set background drawable of a view. There are two methods for this (as far as I see): setBackground and setBackgroundDrawable.

When I use setBackground, it says it has been added in API level 16 but my project's min SDK version is 7. I assume it's not going to work on anything below 16, am I right? But when I use setBackgroundDrawable, it says it's deprecated.

What am I supposed to use?

12条回答
人气声优
2楼-- · 2019-01-01 05:24

you could use setBackgroundResource() instead i.e. relativeLayout.setBackgroundResource(R.drawable.back);

this works for me.

查看更多
骚的不知所云
3楼-- · 2019-01-01 05:26

This works for me: View view is your editText, spinner...etc. And int drawable is your drawable route example (R.drawable.yourDrawable)

 public void verifyDrawable (View view, int drawable){

        int sdk = Build.VERSION.SDK_INT;

        if(sdk < Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackgroundDrawable(
                    ContextCompat.getDrawable(getContext(),drawable));
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackground(getResources().getDrawable(drawable));
        }    
    }
查看更多
人气声优
4楼-- · 2019-01-01 05:29

i know this is an old question but i have a similar situation ,and my solution was

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

and then you can play with the "Drawable", applying color filters, etc

查看更多
听够珍惜
5楼-- · 2019-01-01 05:29

Use ViewCompat.setBackground(view, background);

查看更多
美炸的是我
6楼-- · 2019-01-01 05:32

Now you can use either of those options. And it is going to work in any case. Your color can be a HEX code, like this:

myView.setBackgroundResource(ContextCompat.getColor(context, Color.parseColor("#FFFFFF")));

A color resource, like this:

myView.setBackgroundResource(ContextCompat.getColor(context,R.color.blue_background));

Or a custom xml resource, like so:

myView.setBackgroundResource(R.drawable.my_custom_background);

Hope it helps!

查看更多
萌妹纸的霸气范
7楼-- · 2019-01-01 05:38

seems that currently there is no difference between the 2 functions, as shown on the source code (credit to this post) :

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

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

so it's just a naming decision, similar to the one with fill-parent vs match-parent .

查看更多
登录 后发表回答