简体   繁体   中英

How can I change the image of an ImageView on Android

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>

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.

您是否尝试通过Id引用ImageView而不仅仅是一个新的空白?

ImageView cimg = (ImageView)findViewById(R.id.imageView1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM