setBackgroundDrawable () obsoleto


86

Então, meu SDK vai de 15 para 21 e quando ligo setBackgroundDrawable(), o Android Studio me diz que está obsoleto.

Pensei em contornar isso usando:

int sdk = android.os.Build.VERSION.SDK_INT;

if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_wstat_tstorm));
} else {
    layout.setBackground(getResources().getDrawable(R.drawable.img_wstat_tstorm));
}

Mas então, recebo um erro em "setBackground ()".

Então, como você lidaria com isso?


Você recebe um erro ou um aviso?
— Bryan Herbst

que valor você tem da versão min sdk no manifesto?
— Manmohan Badaya

4
use setbackgroundresource (R.drawable.img_wstat_tstorm); para versão superior.setBackgroundDrawable está obsoleto na versão superior, esta esperança ajuda você
— prakash

O SDk mínimo é 15. Eu tenho "setBackground ()" sublinhado em vermelho, mas o aplicativo é executado, então acho que é um aviso
— Makoto

Você deve obter o Add @SupressWarning
— SweetWisher ツ

Respostas:


105

É um assunto interessante. A maneira como você está fazendo está correta, aparentemente. Na verdade, é apenas uma mudança de decisão de nomenclatura. Como esta resposta indica, setBackground()apenas chama setBackgroundDrawable():

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

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

Você pode ver este tópico para obter mais informações sobre tudo isso.


20
Você deve notar que setBackground()não funcionará para pré API16, uma alternativa poderia sersetBackgroundResource
— Mood

26

talvez você possa tentar o seguinte:

setBackgroundResource(R.drawable.img_wstat_tstorm);

18

É engraçado porque esse método está obsoleto, mas se você olhar o código-fonte do Android, você encontrará o seguinte:

   /**
     * Set the background to a given Drawable, or remove the background. If the
     * background has padding, this View's padding is set to the background's
     * padding. However, when a background is removed, this View's padding isn't
     * touched. If setting the padding is desired, please use
     * {@link #setPadding(int, int, int, int)}.
     *
     * @param background The Drawable to use as the background, or null to remove the
     *        background
     */
    public void setBackground(Drawable background) {
        //noinspection deprecation
        setBackgroundDrawable(background);
    }

12

Correto em 15 de agosto de 2018

Use as bibliotecas de suporte

Drawable drawable = ResourcesCompat.getDrawable(getResources(), drawableRes, null);
ViewCompat.setBackground(layout, drawable);

7

Você está recebendo um erro porque getResources (). GetDrawable () recebe um id (int) e não um drawable como argumento. Experimente isto:

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


setBackground espera apenas Id de sorteio
— SweetWisher ツ

Você está incorreto. Na documentação da API: android.view.View.setBackground (fundo Drawable); Parâmetros: background O Drawable para usar como fundo, ou null para remover o fundo.
— David C Adams

4

Usa isto:

myView.background = ContextCompat.getDrawable(context, R.id.my_drawable)

3
//Java
view.setBackground(ActivityCompat.getDrawable(context, R.drawable.bg))

//Kotlin 
view.background = ActivityCompat.getDrawable(context, R.drawable.bg)

2

Isso está correto no meu caso Resolva este problema

 imageView.setBackgroundResource(images[productItem.getPosition()]);

1

Correto em 23 de novembro de 2018

Kotlin:

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

Se você incluir o parâmetro Theme.


0

Estou usando uma minSdkVersion 16 e targetSdkVersion 23 O seguinte está funcionando para mim, ele usa ContextCompat.getDrawable (context, R.drawable.drawable);

Ao invés de usar: layout.setBackground(getResources().getDrawable(R.drawable.img_wstat_tstorm));

Em vez disso, use:

layout.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable.img_wstat_tstorm));

getActivity() é usado em um fragmento, se chamar de um uso de atividade this


Pergunta feita para minSdk 15
— Harish Gyanani

-1
BitmapDrawable background = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.mipmap.Nome_imgem));
        getSupportActionBar().setBackgroundDrawable(background);

Realmente ajudaria se você
— resumisse
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.