2016-04-28 66 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