How to change ImageView image on Android

I am developing a card game on Android, and I want to change the ImageView image when the button is pressed to select a map, and I considered several other ideas, but all that I have is either a failure 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 the 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> 
+4
source share
2 answers

You have to do

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

In your snippet, you simply create a new ImageView that is not added to the Activity view.

+9
source

Have you tried to reference ImageView by ID, and not just a new empty one?

 ImageView cimg = (ImageView)findViewById(R.id.imageView1); 
+4
source

Source: https://habr.com/ru/post/1342682/


All Articles