2016-04-28 67 views
0

作为我尝试创建内存游戏的一部分,我已在我的布局中放置了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 
      } 
     } 

任何帮助表示赞赏,谢谢!

回答

0

您已声明cards []作为onCreate方法内的局部变量。请在外面声明并尝试。

public class Memory extends AppCompatActivity implements OnClickListener{ 
int[] cards = new int[12]; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_memory); 

    int i; 
      // 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); 
    } 
1

由于您在OnCreate()本地声明卡阵列,因此无法以其他方法访问它。

所有你需要做的就是声明你的卡阵列全局。

public class Memory extends AppCompatActivity implements OnClickListener{ 

    int[] cards; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 

    int i; 
    cards = new int[12]; 
    ... 
} 
+0

这很容易:)现在工作很完美,非常感谢你! – amirtc