2

I tried making an app in which after clicking on the button the image in the background changes to the image cat.png . When I run the app, neither the image in the background comes up nor the the image which is supposed to show up in the place of the background image.

Please see the below code and help.

The onClick function for button is newCat.

    package com.example.imagelesson;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.ImageView;

    public class MainActivity extends AppCompatActivity {


        public void newCat(View view){
            ImageView image = (ImageView)findViewById(R.id.catImgView);
            image.setImageResource(R.drawable.cat);
        }
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    }

activity_main.xml screenshot

Output on emulator

Ticherhaz FreePalestine
  • 2,183
  • 4
  • 18
  • 42
Neha Chaudhary
  • 121
  • 1
  • 11

3 Answers3

0

Click on the search bar and search for onClick property then in onClick field add newCat and then run

click on the search

Furqan Khan
  • 519
  • 4
  • 13
  • @NehaChaudhary is it added to button's onClick field or imageView's. you need to add that to Button's onClick filed. – Furqan Khan Aug 28 '19 at 18:15
0

It'll be mush easier to help you if you show us your xml file.

Anyway:

Firstly, I highly advise you to debug or add log to newCat method so you'll be sure that its being triggered properly.

Then:

Check out this: change-image-of-imageview-programmatically-in-android and that what-is-the-difference-between-imageview-setbackgroundresource-and-imageview-set

San Mo
  • 270
  • 2
  • 11
0

You have added the wrong field. If you take a look in your xml of the layout you should see the following line on the imageview:

tools:srcCompat="your image path"

This is set only when you design the layout. What you need to do is set the image in the previous box:

In XML it should look the following:

app:srcCompat="your image path"

Daniel
  • 1,976
  • 13
  • 25