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?