问题
I just want to change the image on button click using the selector in the XML file. android:state_pressed="true" is working while android:state_selected="true" not working.
Here is my xml code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:state_checked="false"
android:state_focused="false"
android:state_pressed="false"
android:drawable="@drawable/discount1"/>
<item
android:state_pressed="true"
android:drawable="@drawable/discount1"/>
<item
android:drawable="@drawable/discount2"/>
</selector>
Here is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.democoordinatorlayout.MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/buttonselector"
/>
</RelativeLayout>
回答1:
Change your buttonselector to this.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/discount1" /> <!-- pressed state -->
<item android:drawable="@drawable/login" /> <!-- default -->
</selector>
EDIT
To change image of button permanently, use the following code.
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/your_image1"/>
Then in java file, add this:
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
btn.setBackgroundResource(R.drawable.your_image2);
}
});
来源:https://stackoverflow.com/questions/49722355/androidstate-selected-not-working