我正在尝试制作一个简单的井字游戏。我已经写了确定谁获胜的逻辑,并且文本字段显示了获胜者。一旦有人中奖,我就会显示一个重置按钮。并且我已将按钮的onclick属性设置为执行此操作的功能重置
public void reset(View view){
for(int i=0;i<playerAt.length;i++)
playerAt[i]=2;
activeGame=1;
activePlayer=1;
Button but = (Button) findViewById(R.id.button);
TextView text = (TextView) findViewById(R.id.text);
but.setVisibility(View.INVISIBLE);
text.setVisibility(View.INVISIBLE);
GridLayout grid = (GridLayout) findViewById(R.id.grid);
for(int i=0;i<grid.getChildCount();i++){
ImageView block = (ImageView) grid.getChildAt(i);
block.setImageDrawable(null);
}
}
我已经研究了仅在该站点上循环访问网格对象的方法,但似乎无效。我按下按钮后,应用程序将在模拟器中关闭。如果我删除了循环,而是运行了一个简单的循环,如
for(int i=0;i<9;i++)
然后它可以正常工作,但是显然,它什么也不会做。基本上,我希望我的“重置”按钮清除网格布局中的所有条目。我有他们要清除的黑点和红点的图像。
但是这种方式我无法做到。
我也尝试了不使用循环
ImageView block = (ImageView) grid.getChildAt(0);
block.setImageDrawable(null);
但是还是同样的结果:按下按钮后,应用会立即关闭。 可能这不是最新的android studio版本中的方式 如果您想在MainActivity.java文件中查看我的完整代码,则为
package com.example.nik7.tictactoe;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;
import java.nio.InvalidMarkException;
public class MainActivity extends AppCompatActivity {
int activePlayer = 1;
int activeGame = 1;
int [][]winningP = {{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
int []playerAt = {2,2,2,2,2,2,2,2,2};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void drop(View view){
ImageView block = (ImageView) view;
int currentPosition = Integer.parseInt(block.getTag().toString());
if(activeGame==0)
return;
if(playerAt[currentPosition]==1 || playerAt[currentPosition]==0)
return;
playerAt[currentPosition] = activePlayer;
if(activePlayer==1) {
block.setImageResource(R.drawable.black);
activePlayer = 0;
}
else{
block.setImageResource(R.drawable.red);
activePlayer=1;
}
//check if someone has won
for(int[] wp:winningP){
if(playerAt[wp[0]] == playerAt[wp[1]] && playerAt[wp[1]] == playerAt[wp[2]] && playerAt[wp[0]] != 2){
activeGame=0;
Button but = (Button) findViewById(R.id.button);
TextView text = (TextView) findViewById(R.id.text);
but.setVisibility(View.VISIBLE);
text.setVisibility(View.VISIBLE);
text.setText((activePlayer==1)?"red has won":"black has won");
}
}
}
public void reset(View view){
for(int i=0;i<playerAt.length;i++)
playerAt[i]=2;
activeGame=1;
activePlayer=1;
Button but = (Button) findViewById(R.id.button);
TextView text = (TextView) findViewById(R.id.text);
but.setVisibility(View.INVISIBLE);
text.setVisibility(View.INVISIBLE);
GridLayout grid = (GridLayout) findViewById(R.id.grid);
ImageView block = (ImageView) grid.getChildAt(0);
block.setImageDrawable(null);
}
}
答案 0 :(得分:1)
尝试导入
import androidx.gridlayout.widget.GridLayout;
代替
import android.widget.GridLayout;