2016-03-02 31 views
0

想知道通過樣品陣列下面像COLOR1一個爲了該算法循環 - > COLOR3 - >顏色2當按鈕被點擊各一次。我如何週期超過3種類型的值的陣列[機器人]

INT [] colorList =新INT [] {顏色1,顏色2,COLOR3};

目前,我試着做像下面的示例,但無法做到這一點。 如果可能,你會幫我一把嗎?我無法按照我所希望的順序找到解決方案。我很想聽到你的消息!

void updateIndicators(int position) { 
     for (int i = 0; i < indicators.length; i++) { 
      indicators[i].setBackgroundResource(
        i == position ? R.drawable.indicator_selected : R.drawable.indicator_unselected 
     ); 
     } 
    } 
+0

爲什麼你在這裏需要一個週期?如果你只有3個項目,只是硬編碼這些indeces ..它將只有3行代碼。這裏使用循環沒有任何好處。 –

回答

0

也許是這樣的?

public int getNextPosition(int prevPosition){ 
    int maxPosition=2; 
    return (prevPosition+maxPosition)%(maxPosition+1); 
} 

這將返回2當輸入爲0

1當輸入爲2

和0時輸入爲1

所以colorList [0] - > colorList [2] - > colorList [1]

您還可以添加另一個函數返回顏色:

public int nextColor(int prevPosition){ 
    return colorList[getNextPosition(prevPosition)]; 
} 
0

首先你的活動類文件中聲明全局變量,象下面這樣:

int buttonclickcount=0; 

在你clicklistener:

yourbutton.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      buttonclickcount++; 
      if(buttonclickcount%3==0) 
      { 
       //set color 1 from array 
      } 
      else if(buttonclickcount%3==1) 
      { 

       //set color 2 from array 
      } 
      else if(buttonclickcount%3==2) 
      { 

       //set color 3 from array 
      } 
     } 
    });