在做判断点击方块周边是否存在缺口的时候出现问题一点击就报错程序闪退
package com.Pintu.pintu;
import com.example.pintu.R;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
/**利用二维数组创建若干个游戏小方块*/
private ImageView[][] iv_game_arr = new ImageView[3][5];
// 游戏主界面
private GridLayout gl_main_game;
/**当前空方块实例的保存*/
private ImageView iv_null_ImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*初始化游戏的若干个小方块*/
Bitmap bigBm = ((BitmapDrawable)getResources().getDrawable(R.drawable.ic_game_tu)).getBitmap();//获取一张大图
int tuWandH = bigBm.getWidth()/5;//每个游戏小方块的宽和高
for (int i = 0; i < iv_game_arr.length; i++) {
for (int j = 0; j < iv_game_arr[0].length; j++) {
Bitmap bm=Bitmap.createBitmap(bigBm,j*tuWandH,i*tuWandH,tuWandH,tuWandH);//根据航和列切成若干个游戏小图片
iv_game_arr[i][j] = new ImageView(this);
iv_game_arr[i][j].setImageBitmap(bm);
//设置方块之间的间距
iv_game_arr[i][j].setPadding(2, 2, 2, 2);
iv_game_arr[i][j].setTag(new GameData(i, j, bm));//绑定自定义的数据;
iv_game_arr[i][j].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean flag = isHasByNullImageView((ImageView)v);
Toast.makeText(MainActivity.this, "当前位置关系是否存在"+flag, Toast.LENGTH_SHORT).show();
}
});
}
}
// 初始化游戏主界面,并添加若干个小方块
gl_main_game = (GridLayout) findViewById(R.id.gl_main_game);
for (int i = 0; i < iv_game_arr.length; i++) {
for (int j = 0; j < iv_game_arr[0].length; j++) {
gl_main_game.addView(iv_game_arr[i][j]);
}
}
// 设置最后一个方块是空的
setNullImageView(iv_game_arr[2][4]);
}
/*设置某个方块为空方块
@param mImageView 当前设置为空的方块的实例
@return true :相邻,false:不相邻
*/
public void setNullImageView(ImageView mImageView){
mImageView.setImageBitmap(null);
}
//判断当前点击的方块,是否与空方块的位置关系是相关关系
public boolean isHasByNullImageView(ImageView mImageView){
//分别获取当前空方块的位置与点击方块的位置,通过x,y两边都差1的方式判断
GameData mNullGameData = (GameData) iv_null_ImageView.getTag();
GameData mGameData = (GameData)mImageView.getTag();
if(mNullGameData.y==mGameData.y&&mGameData.x+1==mNullGameData.x){//当前点击的方块在空方块的上边
return true;
}else if(mNullGameData.y==mGameData.y&&mGameData.x-1==mNullGameData.x){//当前点击的方块在空方块的下边
return true;
}else if(mNullGameData.y==mGameData.y+1&&mGameData.x==mNullGameData.x){//当前点击的方块在空方块的左边
return true;
}else if(mNullGameData.y==mGameData.y-1&&mGameData.x==mNullGameData.x){//当前点击的方块在空方块的右边
return true;
}
return false;
}
// 每个游戏小方块需要绑定的数据
class GameData{
/**每个小方块的实际位置x*/
public int x =0;
/**每个小方块的实际位置y*/
public int y =0;
/**每个小方块的图片*/
public Bitmap bm;
/**每个小方块的图片位置*/
public int p_x = 0;
/**每个小方块的图片位置*/
public int p_y =0;
public GameData(int x, int y, Bitmap bm) {
super();
this.x = x;
this.y = y;
this.bm = bm;
this.p_x = x;
this.p_y = y;
}
}
}