setBackgroundDrawable () obsoleto


86

Entonces mi sdk va de 15 a 21 y cuando llamo setBackgroundDrawable(), Android Studio me dice que está obsoleto.

Pensé en darle la vuelta 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));
}

Pero luego, aparece un error en "setBackground ()".

Entonces, ¿cómo lidiarías con eso?


¿Recibe un error o una advertencia?
— Bryan Herbst

¿Qué valor tiene la versión min sdk en el manifiesto?
— Manmohan Badaya

4
use setbackgroundresource (R.drawable.img_wstat_tstorm); para una versión superior.setBackgroundDrawable está representado en una versión superior, esta esperanza te ayudará
— prakash

El sdk mínimo es 15. Tengo "setBackground ()" subrayado en rojo, pero la aplicación se ejecuta, así que supongo que es una advertencia
— Makoto

Debes recibir Add @SupressWarning
— SweetWisher ツ

Respuestas:


105

Es un tema interesante. La forma en que lo está haciendo es correcta, aparentemente. En realidad, es solo un cambio de decisión de nomenclatura. Como señala esta respuesta , setBackground()solo llama setBackgroundDrawable():

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

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

Puede ver este hilo para obtener más información sobre todo esto.


20
Debe tener en cuenta que setBackground()no funcionará para versiones anteriores de API16, una alternativa podría sersetBackgroundResource
— Mood

26

tal vez puedas probar lo siguiente:

setBackgroundResource(R.drawable.img_wstat_tstorm);

18

Es gracioso porque ese método está obsoleto, pero si miras el código fuente de Android encontrarás esto:

   /**
     * 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

Correcto al 15 de agosto de 2018

Utilice las bibliotecas de soporte

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

7

Está recibiendo un error porque getResources (). GetDrawable () toma un id (int) no un dibujable como argumento. Prueba esto:

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


setBackground solo espera identificación dibujable
— SweetWisher ツ

Estás equivocado. De los documentos de la API: android.view.View.setBackground (Fondo dibujable); Parámetros: background El Drawable para usar como fondo, o null para quitar el fondo.
— David C Adams

4

Utilizar esta:

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

Esto es correcto en mi caso Resuelve este problema

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

1

Correcto al 23 de noviembre de 2018

Kotlin:

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

Si incluye el parámetro Theme.


0

Estoy usando minSdkVersion 16 y targetSdkVersion 23 Lo siguiente me funciona, usa ContextCompat.getDrawable (context, R.drawable.drawable);

En lugar de usar: layout.setBackground(getResources().getDrawable(R.drawable.img_wstat_tstorm));

Más bien use:

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

getActivity() se usa en un fragmento, si se llama desde una actividad, use this


Pregunta se hace para minSdk 15
— Harish Gyanani

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

Realmente ayudaría si
— resumiera
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.