android:state_selected 不工作

android:state_selected not working

我只想使用 XML 文件中的选择器更改按钮单击时的图像。 android:state_pressed="true" 正在工作,而 android:state_selected="true" 不工作。 这是我的 xml 代码:

<?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>

这里是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>

把你的buttonselector改成这个。

<?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>

编辑

要永久更改按钮的图像,请使用以下代码。

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/your_image1"/>

然后在 java 文件中添加:

Button btn = (Button) findViewById(R.id.button1);

        btn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
               btn.setBackgroundResource(R.drawable.your_image2);
            }
        });