boolean tmp = false;
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tmp = !tmp;
v.setBackgroundColor(tmp ? Color.RED : Color.BLUE);
}
});
编辑:显然你想要一个更复杂的例子
首先创建一个drawable XML并命名Pink_button.xml并将以下代码放入其中
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FF5EF1"/>
<corners android:radius="15dp"/>
<stroke
android:width="1dp"
android:color="#303030"/>
</shape>
现在做一个蓝色按钮.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#008DFF"/>
<corners android:radius="15dp"/>
<stroke
android:width="1dp"
android:color="#303030"/>
</shape>
现在制作一些演示活动布局,我使用了按钮_演示_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/btnDemo"
android:layout_width="150dp"
android:layout_height="30dp"
android:layout_centerInParent="true"
android:layout_marginTop="100dp"
android:background="@drawable/pink_button"
android:gravity="center"
android:text="PINK"
android:textColor="@android:color/white"
android:textSize="15sp"/>
</RelativeLayout>
最后是活动,随意命名我用过的按钮演示活动
public class ButtonDemoActivity extends Activity {
private Button btnDemo;
private boolean isPink = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button_demo_activity);
btnDemo = (Button) findViewById(R.id.btnDemo);
btnDemo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
isPink = !isPink;
int resId = isPink ? R.drawable.pink_button : R.drawable.blue_button;
btnDemo.setBackgroundResource(resId);
btnDemo.setText(isPink ? "PINK" : "BLUE");
}
});
}
}
And this is what the final look of the buttons will be in each state