2011-09-23 12 views
1

當你點擊顏色時應該改爲另一個 但它不起作用! 我的代碼:爲什麼按下時不改變顏色?

public class CreateActivity extends Activity { 

TableLayout table; 
Integer i; 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
     table = (TableLayout)findViewById(R.id.myTable); 

    Button left = (Button) findViewById(R.id.buttonLeft); 
    Button right = (Button) findViewById(R.id.buttonRight); 
    TextView color = (TextView) findViewById(R.id.text); 

    i=0; 

    right.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
      // TODO Auto-generated method stub 
     i++; //+1 
     } 
    }); 
     //COLOR 
    switch(i){ 
    case 1: table.setBackgroundColor(Color.RED); break; 
    case 2: table.setBackgroundColor(Color.rgb (255, 127, 0)); break; 
    case 3: table.setBackgroundColor(Color.YELLOW); break; 
    case 4: table.setBackgroundColor(Color.GREEN) ; break; 
    case 5: table.setBackgroundColor(Color.rgb (0,191,255)); break; 
    case 6: table.setBackgroundColor(Color.BLUE); break; 
    case 7: table.setBackgroundColor(Color.rgb (160,32,240)); break; 

    } 
} 

} 

回答

2

當點擊該按鈕,你遞增i - 但你將不會被再次運行開關/ case語句。如果您查看調試器,您會發現變量值正在改變,但您沒有指示顯示器的任何部分發生更改。

您應該將該公共邏輯放在一個單獨的方法中,該方法從onCreate方法中調用OnClickListener。例如:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    table = (TableLayout)findViewById(R.id.myTable); 

    Button left = (Button) findViewById(R.id.buttonLeft); 
    Button right = (Button) findViewById(R.id.buttonRight); 
    TextView color = (TextView) findViewById(R.id.text); 

    i=0; 

    right.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      i++; 
      // Cycle round 
      if (i == 8) { 
       i = 1; 
      } 
      applyBackgroundColor(); 
     } 
    }); 

    applyBackgroundColor(); 
} 

private void applyBackgroundColor() { 
    switch(i) { 
     // TODO: Consider what you want to do when i is 0... 
     case 1: table.setBackgroundColor(Color.RED); break; 
     case 2: table.setBackgroundColor(Color.rgb(255, 127, 0)); break; 
     case 3: table.setBackgroundColor(Color.YELLOW); break; 
     case 4: table.setBackgroundColor(Color.GREEN); break; 
     case 5: table.setBackgroundColor(Color.rgb(0,191,255)); break; 
     case 6: table.setBackgroundColor(Color.BLUE); break; 
     case 7: table.setBackgroundColor(Color.rgb(160,32,240)); break; 
    } 
} 

有很多其他的事情我會改變這個代碼,但至少應該讓你在這個駝峯。

+0

非常感謝! 但是我也需要改回顏色 –

+0

@Vlad:什麼時候?回到什麼,到底是什麼? –

+0

我有2個按鈕: 左右 左返回最後一個顏色 –

相關問題