Android 如何通过文本更改按钮颜色

Android how to change the button color by the text

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

button.setText("YES");

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

button.setText("NO");

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

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

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

该按钮丢失其 drawable.xml 设置。 有没有办法将此检查添加到可绘制对象 xml? 或者在不丢失可绘制设置的情况下通过其文本值设置背景颜色?

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

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

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

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

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

我在我的 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" />

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