Para establecer el fondo:
RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
¿Es la mejor forma de hacerlo?
RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
¿Es la mejor forma de hacerlo?
Respuestas:
layout.setBackgroundResource(R.drawable.ready);es correcto.
Otra forma de lograrlo es usar lo siguiente:
final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready) );
} else {
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
}
Pero creo que el problema se produce porque estás intentando cargar imágenes grandes.
Aquí hay un buen tutorial sobre cómo cargar mapas de bits grandes.
ACTUALIZACIÓN:
getDrawable (int) en desuso en el nivel 22 de API
getDrawable(int ) ahora está en desuso en el nivel 22 de API. En su lugar, debe usar el siguiente código de la biblioteca de soporte:
ContextCompat.getDrawable(context, R.drawable.ready)
Si hace referencia al código fuente de ContextCompat.getDrawable , le dará 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 API 22, debe usar el getDrawable(int, Theme)método en lugar de getDrawable (int).
ACTUALIZACIÓN:
Si está utilizando la biblioteca de soporte v4, lo siguiente será suficiente para todas las versiones.
ContextCompat.getDrawable(context, R.drawable.ready)
Deberá agregar lo siguiente en su aplicación build.gradle
compile 'com.android.support:support-v4:23.0.0' # or any version above
O usando ResourceCompat, en cualquier API como a continuación:
import android.support.v4.content.res.ResourcesCompat;
ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null);
if(buttonBackground.equals(R.drawable.myDrawable))dónde Drawable buttonBackground = myButton.getBackground();obtengo este error: snag.gy/weYgA.jpg
myActivity.getTheme()la última versión del método, en lugar del parámetro nulo:myView.setBackground( getResources().getDrawable(R.drawable.my_background, activity.getTheme()));
AppCompatResources.getDrawable(this.getContext(), resId)en su lugar, Google ya lo implementó en AppCompat*widget / view, por ejemplo:android.support.v7.widget.AppCompatCheckBox
Prueba esto:
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
y para API 16 <:
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));
getResources().getDrawable(). El código correcto es layout.setBackgroundResource(R.drawable.ready);como el OP usado. El problema aquí proviene del tamaño del mapa de bits.
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 establecer el fondo de cualquier imagen:
View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);
(.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)el código interno
Estoy usando una minSdkVersion 16 y targetSdkVersion 23.
Lo siguiente está funcionando para mí, usa
ContextCompat.getDrawable(context, R.drawable.drawable);
En lugar de usar:
layout.setBackgroundResource(R.drawable.ready);
Más bien uso:
layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));
getActivity()se usa en un fragmento, si se llama desde una actividad, se usa this.
Si sus fondos están en la carpeta dibujable en este momento, intente mover las imágenes de la carpeta dibujable a dibujable-nodpi en su proyecto. Esto funcionó para mí, parece que las imágenes son reescaladas por ellos mismos.
Use 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;
luego 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));
Intenta ViewCompat.setBackground(yourView, drawableBackground)
prueba esto.
int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
preview = (ImageView) findViewById(R.id.preview);
preview.setBackgroundResource(res);
setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));
Dentro de la aplicación / res / your_xml_layout_file .xml
remoteViews.setInt(R.id.btn_start,"setBackgroundResource", R.drawable.ic_button_start);