微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在寻找一种通过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);
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐