我想在每次單擊時在兩個drawable之間添加一個按鈕。我已經有了該背景的XML可繪製代碼和實際按鈕XML。我認爲這對我的Java代碼很不利。單擊時更改按鈕背景
繪製XML
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_star_black_16dp"
android:state_pressed="true" />
<item android:drawable="@drawable/ic_star_black_16dp"
android:state_focused="true" />
<item android:drawable="@drawable/ic_star_border_black_16dp" />
BUTTON XML
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="@drawable/fav"
/>
Java代碼
public void OnClickfav() {
boolean isPressed = false;
but1.setOnClickListener(buttonListener); View.OnClickListener buttonListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isPressed) {
but1.setBackgroundResource(R.drawable.ic_star_border_black_16dp);
} else {
but1.setBackgroundResource(R.drawable.ic_star_black_16dp);
}
isPressed = !isPressed;
}
};
}
使用'setImageResource',而不是'setBackgroundResource'並註冊它之前創建監聽器。 – ex0ns