我正在寻找一种通过onClick更改Button中文本颜色的方法.我想要更改所选按钮文本颜色,并希望其他按钮的文本恢复为默认颜色.这种方式(下面)似乎非常低效.还有更好的方法吗?另外,如何使用onClick恢复原始颜色?
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
TextView textView1 = (TextView) findViewById(R.id.button1);
textView1.setTextColor(Color.RED);
logLevel = "E";
//Change the rest to default (white)
break;
case R.id.button2:
TextView textView2 = (TextView) findViewById(R.id.button2);
textView2.setTextColor(Color.RED);
logLevel = "W";
//Change the rest to white
break;
case R.id.button3:
TextView textView3 = (TextView) findViewById(R.id.button3);
textView3.setTextColor(Color.RED);
logLevel = "D";
//Change the rest to white
break;
case R.id.button4:
TextView textView4 = (TextView) findViewById(R.id.button4);
textView4.setTextColor(Color.RED);
logLevel = "I";
//Change the rest to white
break;
}
retrieveLog(logLevel);
}
解决方法:
Is there a better way to go about it?
步骤#1:将TextView []按钮数据成员添加到活动或片段
步骤#2:在onCreate()中,在setContentView()之后,调用findViewById()四次,每个按钮一次,并将每个按钮放入按钮数组
步骤3:将onClick()重写为:
for (TextView button : buttons) {
if (button==v) {
button.setTextColor(Color.RED);
}
else {
button.setTextColor(Color.WHITE);
}
}