Cambiar el origen de ImageView


Tengo un ImageView con una imagen de origen establecida en el xml usando la siguiente sintaxis:

   <ImageView 
      android:id="@+id/articleImg"
      style="@style/articleImgSmall_2"
      android:src="@drawable/default_m" />

Ahora necesito cambiar esta imagen programáticamente. Lo que necesito hacer es eliminar la imagen antigua y agregar una nueva. Lo que he hecho es esto:

myImgView.setBackgroundResource(R.drawable.monkey);

Funciona, pero me di cuenta de que Android apila la nueva imagen sobre la anterior (no me preguntes cómo descubrí que no es relevante para la discusión :). Definitivamente necesito deshacerme del viejo antes de configurar el nuevo imagen.

¿Cómo puedo lograr eso?

Author: Rüdiger Herrmann, 2010-06-04

8 answers

Cambiando ImageView fuente:

Utilizando setBackgroundResource() método:

  myImgView.setBackgroundResource(R.drawable.monkey);

Estás poniendo a ese mono en el fondo.

Sugiero el uso de setImageResource() método:

  myImgView.setImageResource(R.drawable.monkey);

O con setImageDrawable() método:

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));

*** Con la nueva API de Android 22 getResources().getDrawable() ahora está en desuso. Este es un ejemplo de cómo usarlo ahora:

myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));

Y cómo validar para versiones antiguas de API:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
     myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey, getApplicationContext().getTheme()));
   } else {
     myImgView.setImageDrawable(getResources().getDrawable(R.drawable.monkey));
}
 529
Author: Jorgesys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-12 01:29:42

Se supone que debes usar setImageResource en lugar de setBackgroundResource.

 44
Author: David Hedlund,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-04 14:10:26
myImgView.setImageResource(R.drawable.monkey);

Se utiliza para configurar la imagen en la vista de imagen actual, pero si desea eliminar esta imagen entonces puedes usar este código como:

((ImageView) v.findViewById(R.id.ImageView1)).setImageResource(0);

Ahora esto eliminará la imagen de su vista de imagen, porque ha establecido el valor de recursos a cero.

 25
Author: PIR FAHIM SHAH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-01 04:45:21

Obtener el ID de ImageView como

ImageView imgFp = (ImageView) findViewById(R.id.imgFp);

Luego Use

imgFp.setImageResource(R.drawable.fpscan);

Para establecer la imagen de origen programáticamente en lugar de XML.

 18
Author: Neha Shukla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-22 11:08:48

O prueba este. Para mí está funcionando bien:

imageView.setImageDrawable(ContextCompat.getDrawable(this, image));
 4
Author: radu_paun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-18 14:32:31

Si desea establecer en imageview una imagen que está dentro de los dirs mipmap puede hacerlo así:

myImageView.setImageDrawable(getResources().getDrawable(R.mipmap.my_picture)

 3
Author: commonSenseCode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-08 21:05:47

Simplemente escriba un método para cambiar imageview

public void setImage(final Context mContext, final ImageView imageView, int picture)
{
    if (mContext != null && imageView != null)
    {
        try
        {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            {
                imageView.setImageDrawable(mContext.getResources().getDrawable(picture, mContext.getApplicationContext().getTheme()));
            } else
            {
                imageView.setImageDrawable(mContext.getResources().getDrawable(picture));
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
 2
Author: LOW,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-29 06:58:56

Respuesta visual complementaria

ImageView: setImageResource() (método estándar, relación de aspecto se mantiene)

introduzca la descripción de la imagen aquí

View: setBackgroundResource() (la imagen se estira)

introduzca la descripción de la imagen aquí

Ambos

introduzca la descripción de la imagen aquí

Mi respuesta más completa es aquí .

 0
Author: Suragch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-06 05:29:50