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

标签 java android

我正在寻找一种使用 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/

相关文章:

带有附件 : ClassCastException on javax. mail.Multipart 的 Java 邮件

java - 如何将我的数据库连接放在 .war 文件之外?

android - list 合并失败 : uses-sdk:minSdkVersion 8 cannot be smaller than version 9 declared in library [com. google.android.gms :play-services:7. 8.0]

java - 错误整数自定义值Java

java - 如何在 Android Studio 中使用 ListView 修复 'Incorrect Onclick'

java - java中的itext,不能使用PdfContentByte cb = writer.getDirectContent();

android - 当应用程序在 Android 中处于后台时如何显示启动画面?

android - 如果已缩放,如何在 ImageView 中裁剪位图的可见部分

android - 过滤 SimpleAdapter 时出现 IndexOutOfBoundException

android - ProgressDialog 不会在新线程之前启动