我正在尝试获取目标ID(以ImageView初始化),并将整数ID放入开关盒中,以查看相邻的View,并比较其可绘制对象以确定该玩家是否获胜或游戏是否继续。我将buttonpressed变量初始化为Integer并使用parseInt()获取target的int值。
public void compareButton(int buttonpressed){
//int count = 0;
ImageView adjacent;
ImageView adjacentB;
switch (buttonpressed){
case R.id.imageButtonA: //this is where adjacent buttons are identified and compared
adjacent = findViewById(R.id.imageButtonB);
adjacentB = findViewById(R.id.imageButtonC);
if (target.getDrawable() == adjacent.getDrawable() && target.getDrawable() == adjacentB.getDrawable()) {
Toast.makeText(Mainactivity.this,"You Win!",Toast.LENGTH_SHORT).show(); //Win condition
// } else if (target.getDrawable() == R.id.imageButtonE.getDrawable() & target.getDrawable() == R.id.imageButtonI.getDrawable()) {
//Toast.makeText(Mainactivity.this,Toast.LENGTH_SHORT).show(); //Win condition
// } else if (target.getDrawable() == R.id.imageButtonD.getDrawable() & target.getDrawable() == R.id.imageButtonG.getDrawable()) {
//Toast.makeText(Mainactivity.this,Toast.LENGTH_SHORT).show(); //Win condition
}
break;
case R.id.imageButtonB:
break;
我并不是为了调试而填写所有案例。
我遇到的问题是,当我运行仿真器时,出现错误消息
Caused by: java.lang.NumberFormatException: For input string: "androidx.appcompat.widget.AppCompatImageButton{517eade VFED..C.. ...P..ID 45,381-304,628 #7f070072 app:id/imageButtonA}"
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
at com.example.connect3.Mainactivity.switchColor(Mainactivity.java:75)
这是OnClicklistener的代码:
public void switchColor(View view) {
//Button pressed,depending on user,switch's to that users color; identify adjacent button ID's; toast player control switch
if (player == 1) {
source = findViewById(R.id.yellow);
target = findViewById(view.getId());
target.setImageDrawable(source.getDrawable());
buttonpressed = Integer.parseInt(target.toString());
compareButton(buttonpressed);
player++;
Toast.makeText(Mainactivity.this,"Player 2's Turn!",Toast.LENGTH_SHORT).show();
} else {
source = findViewById(R.id.red);
target = findViewById(view.getId());
target.setImageDrawable(source.getDrawable());
buttonpressed = Integer.parseInt(String.valueOf(target));
compareButton(buttonpressed);
player--;
Toast.makeText(Mainactivity.this,"Player 1's Turn!",Toast.LENGTH_SHORT).show();
}
不能完全确定此时发生了什么,因为我以为我所做的一切都正确,但是显然遗漏了一些东西。任何帮助将不胜感激。