你可以通過以下方法在Android中通過點擊事件改變View的背景色:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:background="@drawable/button_background" />
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/colorAccent" />
<item android:state_focused="true" android:drawable="@color/colorAccent" />
<item android:drawable="@color/colorPrimary" />
</selector>
<color name="colorPrimary">#FF4081</color>
<color name="colorAccent">#3F51B5</color>
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Change background color
v.setBackgroundResource(R.drawable.button_background);
}
});
這樣,當(dāng)Button被點擊時,它的背景色會根據(jù)button_background.xml中定義的顏色變化。