作为我尝试创建内存游戏的一部分,我已在我的布局中放置了12个图像按钮,其ID名称分别为imageButton1 ... imageButton12。我写了一个algrorithm来创建一个名为[12]的随机数组,用来表示哪个卡(card1..card6)位于每个imageButton后面,例如,如果cards [5] = 4,则imageButton6后面的卡是card4。 现在,我试图告诉程序使用数组单击imageButton时显示appropraite卡。我对android studio非常陌生,因为我理解我首先需要在所有按钮上使用OnClickListener,所以我使用循环完成了它。这是到目前为止我的代码:Android - 通过onClick传递数组
public class Memory extends AppCompatActivity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory);
int i;
int[] cards = new int[12];
// Algorithm here
for(i=1;i<=12;i++) {
String name = "imageButton" + i;
int resID = getResources().getIdentifier(name, "id", "com.amir.supermemory");
ImageButton btn = (ImageButton) findViewById(resID);
btn.setOnClickListener(this);
}
现在来的onClick功能,它执行的点击时切换appropraite图像的动作。问题是我无法设法将我之前创建的阵列卡[]传递给函数(它说“无法解析符号'卡片'”),我该怎么做?
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton1:
ImageButton b = (ImageButton) findViewById(R.id.imageButton1);
String name = "card" + cards[0]; //cards is shown in red
int resID = getResources().getIdentifier(name, "drawable", "com.amir.supermemory");
b.setImageResource(resID);
break;
//copy paste forr all imageButtons
}
}
任何帮助表示赞赏,谢谢!
这很容易:)现在工作很完美,非常感谢你! – amirtc