0

How do you make the press of an imageview change another imageviews background image?

My code keeps giving me a null pointer exception error but I dont know why.

The java code

ImageView imageview2 = (ImageView) findViewById(R.id.imageview2);
public void onclickname(View v) {
    imageview2.setImageResource(R.drawable.example);}

The clickable imageview

<ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:clickable="true"
        android:src="@drawable/example"
        android:id="@+id/imageview1"
        android:onClick="onclickname"/>

The imageview whos background image i want to change.

<ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/red"
        android:id="@+id/imageview2"/>

2 Answers2

0

imageview1 and imageview2 are in separate activities.

that's why you are getting null pointer exception.The image view is not found by your activity's layout(It is not appearing on screen). and your imageview2 is always null.

SRB Bans
  • 3,096
  • 1
  • 10
  • 21
  • This isn't the problem as I tried this code with an imageview in the same activity and still got the same error. Do you know a better way to change the background image of a seperate activity? –  Oct 07 '15 at 14:54
0

If you are trying to change the background of a View that is not in your current Activity (not visible) then you could store a flag (boolean) or some int counter which you could pass to the next activity using putExtra.

Then in the onCreate of the second Activity you could use an if statement to check what to set the background to using getExtra after initializing the imageview2.

I think that was the nullPointerException that you were getting.

Community
  • 1
  • 1
eeffoc
  • 468
  • 6
  • 19