gpt4 book ai didi

java - 以编程方式更改按钮文本颜色

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:02 27 4
gpt4 key购买 nike

我正在寻找一种使用 onClick 更改按钮中文本颜色的方法。我希望所选按钮的文本颜色发生变化,而另一个按钮的文本则恢复为默认颜色。这种方式(下图)看起来效率很低。有更好的方法吗?另外,如何使用 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[] buttons 数据成员添加到 Activity 或 fragment

步骤 #2:在 onCreate() 中,在 setContentView() 之后,调用 findViewById() 四次,每个按钮一次,并且将每个按钮放入 buttons 数组

第 3 步:将 onClick() 重写为:

for (TextView button : buttons) {
if (button==v) {
button.setTextColor(Color.RED);
}
else {
button.setTextColor(Color.WHITE);
}
}

关于java - 以编程方式更改按钮文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17031083/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com