第一步:动态生成网格
int scales = 4;//四行四列
TableRow.LayoutParams lpBlock = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);//每网格格式
for (int i = 0;i < scales;i ++){
TableRow curRow = new TableRow(gameActivity);//"gameActivity"添加网格的Activity
for (int j = 0;j < scales;j ++){
ImageView curView = new ImageView(gameActivity);
curView.setId(RES_ID_BASE + i * scales + j);//为每个网格设置下标
curView.setLayoutParams(lpBlock);
curView.setImageBitmap(Bitmap.createBitmap(sourcePicture, j * blockWidth, i * blockHeight, blockWidth, blockHeight));//从大图中取每格图片
curView.setOnClickListener(new OnClickListener() { //每个格子增加事件监听
public void onClick(View v) {//事件实现当点击网格,如果旁边有空格子,就与其交换位置
moveBlockToBlank(v);
}
});
curRow.addView(curView);
}
blocksLayout.addView(curRow);