【问题标题】:Android how to change the button color by the textAndroid如何通过文字改变按钮颜色
【发布时间】:2016-07-12 22:45:45
【问题描述】:

我只是想通过文本的值来改变按钮的背景颜色。例如,当我将文本更改为:

button.setText("YES");

我想将按钮的背景颜色设置为绿色。 当我将文本更改为:

button.setText("NO");

我想将按钮的背景颜色设置为红色

当我像这样在 java 代码中更改它时:

boolean textValueYES = true;
button.setBackgroundColor(textValueYES ? Color.GREEN : Color.RED);

按钮失去其 drawable.xml 设置。 有没有办法将此检查添加到可绘制的 xml 中? 或者通过其文本值设置背景颜色而不丢失可绘制设置?

【问题讨论】:

  • 将按钮背景设置为可绘制使用button.setBackgroundResource(textValueYES ? R.drawable.greendrawable : R.drawable.reddrawable);
  • 创建具有红色背景颜色和绿色背景颜色的可绘制文件,例如:red_drawable.xml,green_drawable.xml,并使用button.setBackgroundResource(R.drawable.red_drawable);

标签: android css colors background drawable


【解决方案1】:

您可以为红色和绿色背景颜色创建两个可绘制 xml,并以编程方式设置该 xml。

button.setBackgroundResource(textValueYES ? R.drawable.green : R.drawable.red);

【讨论】:

    【解决方案2】:

    你必须这样做,只需在 setText() 的下面写

    button.setText("YES");
    setBackgroundResource(R.color.green);
    

    什么时候

    button.setText("NO");
    setBackgroundResource(R.color.red);
    

    【讨论】:

      【解决方案3】:

      我在我的 java 文件中这样做

          final Button btn_showtouch = (Button)findViewById(R.id.button);
          btn_showtouch.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
      
                  if((btn_showtouch.getText()).equals("YES")) {
                      btn_showtouch.setBackgroundColor(Color.GREEN);
                      btn_showtouch.setText("NO");
                  }else if(btn_showtouch.getText().equals("NO")) {
                      btn_showtouch.setBackgroundColor(Color.CYAN);
                      btn_showtouch.setText("YES");
                  }
      
              }
          });
      }
      

      你的 XML 文件是这样的

      <Button
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="YES"
          android:id="@+id/button"
          android:layout_below="@+id/textView"
          android:layout_alignParentLeft="true"
          android:layout_alignParentStart="true"
          android:layout_marginTop="62dp" />
      

      它对我有用,我希望这会对你有所帮助

      【讨论】:

        猜你喜欢
        • 2012-05-02
        • 2018-09-01
        • 2016-12-11
        • 2015-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-11
        • 2015-11-23
        相关资源
        最近更新 更多