我的目标是创建一个图像按钮,并能够在每次单击按钮时更改背景图像。我在访问我在 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:background ?
这是加布对错误的详细回答的进一步说明。
我的方法假设您想在 2 个图像之间更改 ImageButton 的背景,例如image_one
和image_two
。
您需要声明一个变量来保持按钮的状态并切换按钮 - 想想on
并off
切换。
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 Statement而不是If-Statement
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句