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);
}
}
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
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"
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.