2015-11-27 44 views
-1

我在開始時生成了少量隨機數字4,然後如果用戶選擇下一個選項(級別)其5等等...我正在尋找如何檢查數組中第一個生成的數字是什麼,然後執行一個操作,然後在該操作完成後,移動到數組中的第二個數字,依此類推。 生成的數字始終爲1到4,但其數量會發生變化。如何從陣列中獲得第一個數字並對其執行操作

ImageButton 1= (ImageButton) findViewById(R.id.imageButton1); 
ImageButton 2= (ImageButton) findViewById(R.id.imageButton2); 
ImageButton 3= (ImageButton) findViewById(R.id.imageButton3); 
ImageButton 4= (ImageButton) findViewById(R.id.imageButton4); 

↑這些是圖像按鈕我想取決於第一編號的數組 在因此,可以說的是所產生的4個數字是[2,1,2,4] 我想強調

2.setBackgroundColor(0xFF7D0000); 
1.setBackgroundColor(0xFFF000); 
2.setBackgroundColor(0xFF7D0000); 
4.setBackgroundColor(0x0000FF); 

我想要上面的顏色改變1秒,然後移動到數組中的下一個顏色。

這裏的地方產生的數量和其中的代碼應該去

int value; 
     TextView textTest = (TextView)findViewById(R.id.textViewTesting); 

     StringBuilder builder = new StringBuilder(); 

     int[] NumbersArray = new int[20]; 

     for (int num = 0; num < 4 +temp; num++) 
{ 
      value = (int) (Math.random() * 4 + 1); 

      builder.append(value + " "); 
      textTest.setText(builder.toString()); 
      NumbersArray[num] = value; 
      System.out.println(NumbersArray[num]); 
} 

回答

2

數值不是有效的變量名,

ImageButton 1= (ImageButton) findViewById(R.id.imageButton1); 

是無效的。

試試這個:

ArrayList<ImageButton> listOfButtons = new ArrayList<ImageButton>(); 


//adds R.id.imageButton1 at first position of your list 
listOfButtons.add((ImageButton) findViewById(R.id.imageButton1)); 

//adds R.id.imageButton5 at second position of your list 
listOfButtons.add((ImageButton) findViewById(R.id.imageButton5)); 

//adds R.id.imageButton3 at thirdposition of your list 
listOfButtons.add((ImageButton) findViewById(R.id.imageButton3)); 


//firstItem is R.id.imageButton1 
ImageButton firstItem = listOfButtons.get(0); 

//secondItem is R.id.imageButton5 
ImageButton secondItem = listOfButtons.get(1); 
.... 
int index;//index should never exceed list size 
.... 
ImageButton selectedByIndex = listOfButtons.get(index); 
+0

很抱歉的數值。我把它們作爲我的代碼中的文本,但仍然你上面提到的代碼不適合我,我得到'index'的錯誤,並且我得到'selectedByIndex'的錯誤以及...'= new ArrayList ' – TroubleSome

+0

這讓你知道該怎麼做。顯然索引在我的例子中沒有被初始化,我不知道你想要檢索哪個索引。如果你想要第一個元素索引= 0;如果你想要第二個元素index = 1,如果你想要最後一個元素index = listOfButtons.size() - 1;也爲arraylist工作,你顯然需要import java.util.ArrayList; – ForeverStudent

+0

我導入ArrayList,但我不知道如何以及在哪裏把你的建議放入我的代碼。過去3周我一直在做Android java,對於如何實現我想要做的事情一無所知。您能否根據我上面的代碼告訴我如何根據數組中的數字來改變按鈕的顏色, – TroubleSome

相關問題