Cómo configurar la imagen de forma dinámica en android?

Estoy almacenando imágenes relacionadas con mi proyecto en una carpeta dibujable. También estoy almacenando los nombres de la imagen en variable de la secuencia y dinámicamente estoy intentando fijar esas imágenes a la visión de la imagen. Pero la imagen no se muestra. Por favor, ayúdame en este sentido.

Mi código:

int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName()); imageview= (ImageView)findViewById(R.id.imageView); imageview.setImageResource(res); 

En el código anterior "imagename" es la variable de cadena que contiene el nombre de la imagen.

Gracias por adelantado

Prueba esto:

 String uri = "@drawable/myresource"; // where myresource (without the extension) is the file int imageResource = getResources().getIdentifier(uri, null, getPackageName()); imageview= (ImageView)findViewById(R.id.imageView); Drawable res = getResources().getDrawable(imageResource); imageView.setImageDrawable(res); 

Aquí estoy fijando la imagen frnd_inactive a la imagen

  imageview= (ImageView)findViewById(R.id.imageView); imageview.setImageDrawable(getResources().getDrawable(R.drawable.frnd_inactive)); 
 imageview= (ImageView)findViewById(R.id.imageView); imageview.setImageResource(R.drawable.mydrawable) 

Prueba este código dinámico

 String fnm = "cat"; // this is image file name String PACKAGE_NAME = getApplicationContext().getPackageName(); int imgId = getResources().getIdentifier(PACKAGE_NAME+":drawable/"+fnm , null, null); System.out.println("IMG ID :: "+imgId); System.out.println("PACKAGE_NAME :: "+PACKAGE_NAME); // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),imgId); your_image_view.setImageBitmap(BitmapFactory.decodeResource(getResources(),imgId)); 

En el código anterior necesitará Image-file-Name y Image-View objeto que ambos están teniendo .

Vea abajo el código esto está trabajando para mí

 iv.setImageResource(getResources().getIdentifier( "imagename", "drawable", "com.package.application")); 

Aquí está la mejor manera que funciona en cada teléfono en la actualidad . La mayoría de las respuestas están obsoletas o necesitan una API> = 19 o 22. Puede usar el código de fragmento o el código de actividad depende de lo que necesita.

Fragmento

 //setting the bitmap from the drawable folder Bitmap bitmap= BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.my_image); //set the image to the imageView imageView.setImageBitmap(bitmap); 

Actividad

 //setting the bitmap from the drawable folder Bitmap bitmap= BitmapFactory.decodeResource(MyActivity.this.getResources(), R.drawable.my_image); //set the image to the imageView imageView.setImageBitmap(bitmap); 

¡Aclamaciones!

Esto funciona para mí (no utilizar la extensión de la imagen, sólo el nombre):

 String imagename = "myImage"; int res = getResources().getIdentifier(imagename, "drawable", this.getPackageName()); imageview= (ImageView)findViewById(R.id.imageView); imageview.setImageResource(res); 
 imageView.setImageResource(R.drawable.picname); 

Primero de su nombre de la imagen es myimage . Así que lo que tienes que hacer es ir a Drawable y guardar el nombre de la imagen myimage .

Ahora suponga que solo conoce el nombre de la imagen y necesita acceder a él. Utilice el siguiente fragmento para acceder a él,

Lo que hizo es correcto, asegúrese de guardar el nombre de imagen que va a utilizar dentro de la codificación.

 public static int getResourceId(Context context, String name, String resourceType) { return context.getResources().getIdentifier(toResourceString(name), resourceType, context.getPackageName()); } private static String toResourceString(String name) { return name.replace("(", "") .replace(")", "") .replace(" ", "_") .replace("-", "_") .replace("'", "") .replace("&", "") .toLowerCase(); } 

Además de que usted debe asegurarse de que no hay espacios vacíos y sensitivos caso

A partir de la API 22, getResources().getDrawable() está obsoleto (vea también Android getRapport () getDrawable () API obsoleto 22 ). Esta es una nueva forma de configurar dinámicamente el recurso de imagen:

 String resourceId = "@drawable/myResourceName"; // where myResourceName is the name of your resource file, minus the file extension int imageResource = getResources().getIdentifier(resourceId, null, getPackageName()); Drawable drawable = ContextCompat.getDrawable(this, imageResource); // For API 21+, gets a drawable styled for theme of passed Context imageview = (ImageView) findViewById(R.id.imageView); imageview.setImageDrawable(drawable); 

Esto funciona bien para mi.

 final R.drawable drawableResources = new R.drawable(); final Class<R.drawable> c = R.drawable.class; final Field[] fields = c.getDeclaredFields(); for (int i=0; i < fields.length;i++) { resourceId[i] = fields[i].getInt(drawableResources); /* till here you get all the images into the int array resourceId.*/ } imageview= (ImageView)findViewById(R.id.imageView); if(your condition) { imageview.setImageResource(resourceId[any]); } 

GetDrawable () está obsoleto. Ahora puedes usar

 imageView.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.msg_status_client_read)) 

getDrawable() está obsoleto, así que intenta esto

 imageView.setImageResource(R.drawable.fileName) 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.