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);
  }
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...