【发布时间】:2016-04-28 22:28:43
【问题描述】:
作为我尝试创建记忆游戏的一部分,我在布局上放置了 12 个图像按钮,ID 名称为 imageButton1...imageButton12。我编写了一个算法来创建一个名为cards[12] 的数组,它使用随机值来表示每个imageButton 后面的卡片(card1..card6),例如,如果cards[5]=4,那么imageButton6 后面的卡片就是card4。 现在,我试图告诉程序在使用数组单击 imageButton 时显示适当的卡片。我对 android studio 很陌生,据我所知,我首先需要在所有按钮上使用 OnClickListener,所以我使用循环完成了它。到目前为止,这是我的代码:
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 函数,它执行点击时切换相应图像的动作。问题是我无法将之前创建的数组cards[]传递给函数(它说“无法解析符号'cards'”),我该怎么做?
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
}
}
感谢您的帮助,谢谢!
【问题讨论】:
标签: android