Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the image of an ImageView on Android

Tags:

android

image

I am developing a card game on android, and I am looking to change the Image of an ImageView when a button is pressed to pick a card, and I have looked at several other ideas, but all I have seem either crash or it does not change.

    cimg = new ImageView(this);
    nextCard.setOnClickListener(new View.OnClickListener() 

    {
        public void onClick(View v) 
        {
            cimg.setImageResource(R.drawable.c2);
            doCard();
        }
    });

Here is what I have for code, and with this, the image does not change XML:

    <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content"    android:src="@drawable/icon" android:id="@+id/imageView1"></ImageView>
like image 908
Greg Kolesar Avatar asked Mar 07 '11 18:03

Greg Kolesar


2 Answers

You have to do

cimg = findViewById(R.id.imageView1); // in your onCreate

cimg.setImageResource(R.drawable.c2);

In your snippet you are just creating a new ImageView that isn't added to your Activity's view.

like image 144
Robby Pond Avatar answered Nov 02 '22 22:11

Robby Pond


have you tried referencing the ImageView by Id rather than just a new blank one?

ImageView cimg = (ImageView)findViewById(R.id.imageView1);
like image 39
Peter Avatar answered Nov 02 '22 22:11

Peter