2015-11-23 54 views
0

添加視圖到一個數組,我有以下按鈕意見Android的 - 使用for循環

button1 = (Button) findViewById(R.id.button0); 
button2 = (Button) findViewById(R.id.button1); 
button3 = (Button) findViewById(R.id.button2); 
button4 = (Button) findViewById(R.id.button3); 
button5 = (Button) findViewById(R.id.button4); 
button6 = (Button) findViewById(R.id.button5); 
button7 = (Button) findViewById(R.id.button6); 
button8 = (Button) findViewById(R.id.button7); 

,這個按鈕[]:

Button[] buttonViewsArray = new Button[8]; 

我想用一個for循環來補充按鈕進入陣列,但不知道如何使用變量i然後引用正確的按鈕:

int i; 
    for (i = 0; i < buttonViewsArray.length; i++){ 
    String j = "button" + i; 
    Button[i] = findViewById(j); 
    } 

我以爲可能會創建一個String,它引用了正確的viewID?

+0

互聯網,你可以找到一堆類似或相同的例子,問題 –

+0

你可以做到這一點的一行代碼,如果你不使用循環或簡單地使用按鈕ArrayList。 – Arslan

回答

0

不,R.id.button6是R文件中的整數。

如果需要,您必須爲每個按鈕調用findViewById並將它們保存在數組中。

0

是的,可以在循環中獲取資源。下面是一個數獨的應用程序我放在一起的例子(TextViews有形式「TV32」的名稱):

// get the text views using dynamic layout IDs 
for(int row=0; row<9; row++) 
    for(int col=0; col<9; col++) 
    { 
     int layoutID = getResources().getIdentifier("tv"+row+col, "id", getPackageName()); 
     tv[row][col] = (TextView) findViewById(layoutID); 
     // set text for testing 
     //tv[row][col].setText(""+row+col); 
     // set up to respond to click 
     tv[row][col].setOnClickListener(new CellOnClickListener(row, col)); 
    }