如何在 Android 中使用 onclick 更改按钮的背景可绘制对象?

How can I change the Background drawable of my button with onclick in Android?

我有一个带有可绘制对象的按钮 XML 背景

android:background="@drawable/greenbut"

我想通过单击我的按钮将背景更改为我的 @drawable/yellowbut

我用这段代码试了一下,但好像完全错了。我无法使用 setBackground Function。你能帮忙吗..?

public void colorChanger(View v)
{
    Button changeBut = (Button) findViewById(R.id.button2);
    changeBut.setBackground(R.drawable.yellowbut);
    changeBut.isClickable();
}

试试这个

public void colorChanger(View v)
{
 Button changeBut = (Button) findViewById(R.id.button2);
 changeBut.setBackgroundResource(R.drawable.yellowbut);
 changeBut.isClickable();
}

就这么简单,跟着代码走希望对你有帮助

setContentView(R.layout.activity_main);
        final Button changeBut = (Button) findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                button.setBackgroundColor(Color.yellow);
            }
        });