My goal is to create an image button and be able to change the background image each time the button is clicked. I was having trouble accessing the ImageButton that I designed inside the activity_main.xml file.
This is the MainActivity.java file
package com.example.imageButtonTest;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void foo(View v) {
ImageButton myButton = new ImageButton(); //error here, might have to pass something inside Imagebutton()
if(v.getId() == R.id.image_1) { //check if button is clicked
myButton.setImageResource(R.drawable.imageName); //update to new image (imageName)
}
}
}
And this is the activity_main.xml where the ImageButton is declared:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageButton
android:id="@+id/image_1"
android:tag="12"
android:onClick="foo"
android:background="@drawable/image_1"
android:layout_width="50dp"
android:layout_height="50dp">
</ImageButton>
</LinearLayout>
This is the error:
Cannot resolve constructor 'ImageButton()'
How can I properly initialize ImageButton so I can change its android:background each time the button is clicked?
2
Answers
ImageButton doesn’t have a 0 argument constructor. No View does. They all take a Context at a minimum. new ImageButton(this) would compile. It still wouldn’t do what you want though. There is no reason to create a new view here at all. Instead what you want to do is
This will change the image of the existing view. Creating a new button and setting the image on that would do nothing, as your new view isn’t in the displayed view root.
This is further to Gabe’s detailed answer on the error.
My approach assumes you want to change the ImageButton’s background between 2 images say
image_one
andimage_two
.You need to declare a variable to hold the state of the button and toggle the Button – think of
on
andoff
switch.If you have multiple images to set on the button you can go for the Switch Statement instead of
If-Statement
.