setBackgroundDrawable() deprecated

前端 未结 11 1627
长发绾君心
长发绾君心 2020-12-03 00:18

So my sdk goes from 15 to 21 and when I call setBackgroundDrawable(), Android Studio tells me that it\'s deprecated.

I thought of going around it using:

相关标签:
11条回答
  • 2020-12-03 01:02

    You are getting an error because getResources().getDrawable() takes an id (int) not a drawable as its argument. Try this:

    layout.setBackground(getResources().getDrawable(R.id.img_wstat_tstorm));

    0 讨论(0)
  • 2020-12-03 01:06

    Correct as of 23th November 2018

    Kotlin:

    view.background = resources.getDrawable(R.drawable.ic_image,theme)
    

    If you include the Theme parameter.

    0 讨论(0)
  • 2020-12-03 01:08

    It's an interesting topic. The way you are doing it is correct, apparently. It is actually just a naming decision change. As this answer points out, setBackground() just calls setBackgroundDrawable():

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

    You can see this thread for more information about all of this.

    0 讨论(0)
  • 2020-12-03 01:08

    Correct as of 15th August 2018

    Use the support libraries

    Drawable drawable = ResourcesCompat.getDrawable(getResources(), drawableRes, null);
    ViewCompat.setBackground(layout, drawable);
    
    0 讨论(0)
  • 2020-12-03 01:08
    //Java
    view.setBackground(ActivityCompat.getDrawable(context, R.drawable.bg))
    
    //Kotlin 
    view.background = ActivityCompat.getDrawable(context, R.drawable.bg)
    
    0 讨论(0)
提交回复
热议问题