2011-09-23 57 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个按钮: 左右 左返回最后一个颜色 –

相关问题