greenpool
greenpool

Reputation: 561

Changing imageview on button click android

I'm attempting to to change the image when the button is clicked. In the learning curve at the moment so having trouble identifying why its failing.

Here's my code:

public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    Button changeMebtn = (Button) findViewById(R.id.changeMe);

    changeMebtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            ImageView image = (ImageView) findViewById(R.drawable.amsterdam);
            image.setImageResource(R.drawable.lima);
        }
    });


}

}

XML:

 <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/amsterdam" />

    <Button
        android:id="@+id/changeMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Me" 
        android:layout_gravity="center"/>

I'm currently getting an generic error when i click the button.

Can somebody tell me what i'm doing wrong here...?

Thanks.

Upvotes: 0

Views: 18734

Answers (3)

Nitesh Chaudhary
Nitesh Chaudhary

Reputation: 31

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

Upvotes: 0

Nermeen
Nermeen

Reputation: 15973

Use:

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

Upvotes: 4

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

use

 ImageView image = (ImageView) findViewById(R.id.imageView1);
            image.setImageResource(R.drawable.lima);

instead of

 ImageView image = (ImageView) findViewById(R.drawable.amsterdam);
            image.setImageResource(R.drawable.lima);

because your image id is imageView1 in xml not amsterdam

and second point use R.id.imageView1 instead of R.drawable.amsterdam

Upvotes: 15

Related Questions