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

4

我只是希望根据文本的值更改按钮的背景颜色。例如,当我把文本更改为:

button.setText("YES");

我可以帮您将按钮的背景颜色设置为绿色,并且当更改文本时:
button.setText("NO");

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

当我在Java代码中进行更改时,如下所示:

boolean textValueYES = true;
button.setBackgroundColor(textValueYES ? Color.GREEN : Color.RED);
失去了其drawable.xml的设置。 有没有一种方法可以将此检查添加到drawable xml中? 或者通过文本值设置背景颜色而不会失去drawable设置?

要将按钮背景设置为可绘制,请使用 button.setBackgroundResource(textValueYES ? R.drawable.greendrawable : R.drawable.reddrawable); - Ahsan Kamal
创建带有红色背景和绿色背景的可绘制文件,例如:red_drawable.xml、green_drawable.xml,并使用button.setBackgroundResource(R.drawable.red_drawable)。 - Norutan
3个回答

4
你可以创建两个drawable xml文件分别设置红色和绿色背景,并通过编程方式来设置这些xml。
button.setBackgroundResource(textValueYES ? R.drawable.green : R.drawable.red);

3
你需要像这样操作,在setText()下面直接编写代码。
例如:
button.setText("YES");
setBackgroundResource(R.color.green);

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

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接