android:state_selected not working

二次信任 提交于 2019-12-11 14:22:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!