无法解析构造函数'ImageButton()'



我的目标是创建一个图像按钮,并且能够在每次单击按钮时更改背景图像。我在访问我在activity_main.xml文件中设计的ImageButton时遇到了麻烦。

是MainActivity.java文件

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)
}
}
}

下面是声明ImageButton的activity_main.xml:

<?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>

错误:

Cannot resolve constructor 'ImageButton()'

我怎么能正确地初始化ImageButton,这样我就可以改变它的android:背景每次按钮被点击?

ImageButton没有一个0参数的构造函数。没有视图。它们都至少需要一个上下文。new ImageButton(this)将编译。但它仍然不会做你想要的。在这里根本没有理由创建一个新视图。你要做的是

public void foo(View v) {
ImageButton myButton = (ImageButton)v;
myButton.setImageResource(R.drawable.imageName)
}

这将改变现有视图的图像。创建一个新按钮并在上面设置图像不会做任何事情,因为您的新视图不在显示的视图根中。

这是Gabe对错误的详细回答。

我的方法假设你想改变ImageButton的背景之间的2图像说image_oneimage_two

你需要声明一个变量来保持按钮的状态和切换按钮-想想onoff切换。

public class MainActivity extends AppCompatActivity {
//declare ImageButton here
ImageButton imageButton;
//variable for toggling state
boolean isClicked = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize ImageButton here
imageButton = findViewById(R.id.image_1);
}
public void foo(View v) {
//if statement to check state of the button
if (isClicked) {
imageButton.setImageResource(R.drawable.image_one);
//reverse button state
isClicked = false;
} else {
imageButton.setImageResource(R.drawable.image_two);
//reverse button state
isClicked = true;
}
}
}

如果你有多个图像要设置在按钮上,你可以选择Switch语句而不是If-Statement