Cómo definir el fondo dibujable mediante programación en Android

Para configurar el fondo:

RelativeLayout layout =(RelativeLayout)findViewById(R.id.background); layout.setBackgroundResource(R.drawable.ready); 

¿Es la mejor manera de hacerlo?

layout.setBackgroundResource(R.drawable.ready); es correcto.
Otra forma de lograrlo es utilizar lo siguiente:

 final int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { layout.setBackgroundDrawable( getResources().getDrawable(R.drawable.ready) ); } else { layout.setBackground( getResources().getDrawable(R.drawable.ready)); } 

Pero creo que el problema se produce porque está intentando cargar imágenes grandes.
Aquí hay un buen tutorial sobre cómo cargar grandes mapas de bits.

ACTUALIZAR:
GetDrawable (int) obsoleto en el nivel 22 de la API

getDrawable(int ) está ahora obsoleto en el nivel 22 de API. Debería utilizar el siguiente código de la biblioteca de soporte:

 ContextCompat.getDrawable(context, R.drawable.ready) 

Si te refieres al código fuente de ContextCompat.getDrawable , te da algo como esto:

 /** * Return a drawable object associated with a particular resource ID. * <p> * Starting in {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the returned * drawable will be styled for the specified Context's theme. * * @param id The desired resource identifier, as generated by the aapt tool. * This integer encodes the package, type, and resource entry. * The value 0 is an invalid identifier. * @return Drawable An object that can be used to draw this resource. */ public static final Drawable getDrawable(Context context, int id) { final int version = Build.VERSION.SDK_INT; if (version >= 21) { return ContextCompatApi21.getDrawable(context, id); } else { return context.getResources().getDrawable(id); } } 

Más detalles sobre ContextCompat

A partir de la API 22, debe utilizar el getDrawable(int, Theme) lugar de getDrawable (int).

ACTUALIZAR:
Si está utilizando la biblioteca de soporte v4, lo siguiente será suficiente para todas las versiones.

 ContextCompat.getDrawable(context, R.drawable.ready) 

Tendrás que añadir lo siguiente en tu aplicación build.gradle

 compile 'com.android.support:support-v4:23.0.0' # or any version above 

O utilizando ResourceCompat, en cualquier API como a continuación:

 import android.support.v4.content.res.ResourcesCompat; ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null); 

Prueba esto:

 layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready)); 

Y para API 16 <:

 layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready)); 
 RelativeLayout relativeLayout; //declare this globally 

Ahora, dentro de cualquier función como onCreate, onResume

 relativeLayout = new RelativeLayout(this); relativeLayout.setBackgroundResource(R.drawable.view); //or whatever your image is setContentView(relativeLayout); //you might be forgetting this 

También puede configurar el fondo de cualquier imagen:

 View v; Drawable image=(Drawable)getResources().getDrawable(R.drawable.img); (ImageView)v.setBackground(image); 

Si sus fondos se encuentran en la carpeta dibujable ahora intente mover las imágenes de drawable a drawable-nodpi carpeta en su proyecto. Esto funcionó para mí, parece que el resto de las imágenes son reescaladas por ellos mismos ..

Estoy usando un minSdkVersion 16 y targetSdkVersion 23 Lo siguiente está funcionando para mí, utiliza ContextCompat.getDrawable (context, R.drawable.drawable);

En lugar de usar:
layout.setBackgroundResource(R.drawable.ready);

Utilice más bien:

layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));

getActivity() se utiliza en un fragmento, si llama de una actividad use this

Utilice butterknife para vincular el recurso extraíble a una variable agregando esto a la parte superior de su clase (antes de cualquier método).

 @Bind(R.id.some_layout) RelativeLayout layout; @BindDrawable(R.drawable.some_drawable) Drawable background; 

Entonces dentro de uno de sus métodos agregue

 layout.setBackground(background); 

Eso es todo lo que necesitas

 if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ready)); else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) layout.setBackground(getResources().getDrawable(R.drawable.ready)); else layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready)); 

Pruebe este código:

 Drawable thumb = ContextCompat.getDrawable(getActivity(), R.mipmap.cir_32); mSeekBar.setThumb(thumb); 

Pruebe a ViewCompat.setBackground(yourView , drawableBackground)

  • ¿Cómo puedo hacer conexiones de URL asíncronas en Android?
  • Cómo obtener una respuesta JSON grande en Android Sybase Unwired Platform
  • La API de Google Maps para Android no funciona con debug.keystore
  • Android Studio, Java 8 y Función
  • Reemplazar espacio a guión
  • Parse crash en la creación de usuario
  • XML con la biblioteca SimpleXML - Rendimiento en Android
  • Un método más eficiente de dibujar miles de partículas (Java / Android)
  • ProgressDialog Actividad de fondo Fade Out Animation
  • ¿Cómo puedo detectar una versión de mi aplicación?
  • Cómo cambiar la opacidad de un mapa de bits?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.