作爲我嘗試創建內存遊戲的一部分,我已在我的佈局中放置了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