[英]Button text color change programmatically
我正在寻找一种通过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);
}
还有更好的方法吗?
步骤#1:将TextView[] buttons
数据成员添加到活动或片段
步骤#2:在onCreate()
,在setContentView()
,调用findViewById()
四次,每个按钮一次,并将每个按钮放入buttons
数组
步骤3:将onClick()
重写为:
for (TextView button : buttons) {
if (button==v) {
button.setTextColor(Color.RED);
}
else {
button.setTextColor(Color.WHITE);
}
}
与drawable一样,Android也允许您为文本颜色设置选择器。 这样你就不必担心以编程方式改变颜色,因为框架会处理这个问题。
例如,在res/color/text_color_selector.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#000000" /> <!-- pressed -->
<item android:state_focused="true"
android:color="#000000" /> <!-- focused -->
<item android:color="#FFFFFF" /> <!-- default -->
</selector>
然后像任何其他颜色一样引用它:
<Button ...
android:textColor="@color/text_color_selector" />
来源: Android选择器和文字颜色
编辑:我可能误解了最初的问题,因为您似乎想要在点击后保留更改的文本颜色。 您可能仍然可以使用上面的内容,但将Button
更改为支持已检查状态的内容。 这意味着,如果选中,您将拥有一种颜色,并且在取消选中其反转版本时。 显然,您可以将结果设置为看起来像普通按钮(没有实际的复选标记)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.