加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 05:00:54 所属栏目:Java 来源:网络整理
导读:我正在寻找一种通过onClick更改Button中文本颜色的方法.我想要更改所选按钮文本颜色,并希望其他按钮的文本恢复为默认颜色.这种方式(下面)似乎非常低效.还有更好的方法吗?另外,如何使用onClick恢复原始颜色? public void onClick(View v) { switch (v.getId
我正在寻找一种通过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);
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读