应更改为另一个 但它不起作用! 我的代码:
# 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;
}
}
}
答案 0 :(得分:2)
单击该按钮时,您正在递增i
- 但您不会再次运行switch / case语句。如果您查看调试器,您会发现变量值正在发生变化,但您没有指示 display 的任何部分进行更改。
您应该将该通用逻辑放在一个单独的方法中,该方法从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;
}
}
关于这段代码我还有其他各种改变,但这至少应该让你超越这个驼峰。