Android: ¿Configurar la imagen de fondo para RelativeLayout?
-
29-10-2019 - |
Pregunta
He descargado una imagen en tiempo de ejecución.Ahora quiero establecerlo como fondo para RelativeLayout
.¿Es posible?
Solución
Consulte el setBackgroundDrawable , o quizás createFromPath en la clase Drawable.
RelativeLayout rLayout = (RelativeLayout) findViewById (R.id.rLayout);
Resources res = getResources(); //resource handle
Drawable drawable = res.getDrawable(R.drawable.newImage); //new Image that was added to the res folder
rLayout.setBackground(drawable);
Otros consejos
En su lugar, utilice:
View lay = (View) findViewById(R.id.rLayout);
lay.setBackgroundResource(R.drawable.newImage);
Esto funciona porque R.drawable.newImage
se refiere a un número entero.Entonces podrías hacer:
int pic = R.drawable.newImage;
lay.setBackgroundResource(pic);
Pruebe esto para Xamarin.Android (multiplataforma) -
RelativeLayout relativeLayout = new RelativeLayout (this);
O
RelativeLayout relativeLayout = (RelativeLayout)FindViewById (Resource.Id.relativeLayout);
Y
relativeLayout.SetBackgroundDrawable (Resources.GetDrawable (Resource.Drawable.imageName));
En la función onCreate:
RelativeLayout baseLayout = (RelativeLayout) this.findViewById(R.id.the_layout_id);
Drawable drawable = loadImageFromAsset();
if(drawable != null){
baseLayout.setBackground(drawable);
Log.d("TheActivity", "Setting the background");
}
El método de carga de imágenes:
public Drawable loadImageFromAsset() {
Drawable drawable;
// load image
try {
// get input stream
InputStream ims = getAssets().open("images/test.9.png");
//Note: Images can be in hierarical
// load image as Drawable
drawable = Drawable.createFromStream(ims, null);
}
catch(IOException ex) {
Log.d("LoadingImage", "Error reading the image");
return null;
}
return drawable;
}
El método abierto:
> public final InputStream open (String fileName, int accessMode)
>
> Added in API level 1 Open an asset using an explicit access mode,
> returning an InputStream to read its contents. This provides access to
> files that have been bundled with an application as assets -- that is,
> files placed in to the "assets" directory.
>
> fileName --- The name of the asset to open. This name can be hierarchical.
>
> accessMode --- Desired access mode for retrieving the data.
>
> Throws IOException
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow