Java android-自定义按钮(使用选择器文件)不工作

Java android-自定义按钮(使用选择器文件)不工作,java,android,android-studio,button,custom-button,Java,Android,Android Studio,Button,Custom Button,我正在尝试创建一个“添加到收藏夹”按钮 问题是,除非我一直按下按钮,否则牵引装置不会改变。一旦我松开按钮,它就会返回到原来的可绘制状态 我遵循了本教程:但得到了不同的结果 我创建了一个res/drawable/custom_fav_button.xml文件 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.

我正在尝试创建一个“添加到收藏夹”按钮

问题是,除非我一直按下按钮,否则牵引装置不会改变。一旦我松开按钮,它就会返回到原来的可绘制状态

我遵循了本教程:但得到了不同的结果

我创建了一个res/drawable/custom_fav_button.xml文件

<?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/ic_baseline_favorite_24"/>

    <item
        android:drawable="@drawable/ic_baseline_favorite_border_24"/>

</selector>

我正在一项活动中使用它,如下所示

<Button
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:background="@drawable/custom_fav_button"/>


提前谢谢

正如您在视频中所看到的,您的代码运行良好,并执行您所说的操作。只有在按下时才能更改。如果您想在单击后更改它,那么应该添加可绘制的xml

可绘制按钮选择器.xml

 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/drawable_button_selected" android:state_selected="true" />
    <item android:drawable="@drawable/drawable_button_unselected" android:state_selected="false" />
    <item android:drawable="@drawable/drawable_button_unselected" />
</selector>

当按钮启用时,此操作仅工作一次。之后,按钮将不工作,因为它未启用。我想它改变图片每次点击。类似于Facebook或Instagram上的“喜欢”按钮。@Maryam Wael请查看我的最新答案。如果您尝试代码,您可以看到它工作得很好,并使您想要的。颜色是随机的,我添加了一个祝酒词,看看它是否真的有效。效果非常好。谢谢
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    
    <!-- color of the selected button -->
    <solid
        android:color="@color/purple_200"/>

</shape
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">


    <!-- unselected button background -->
    <solid
        android:color="@color/gray_dove_three" />

    <stroke
        android:color="@color/gray_martini"
        android:width="2dp"/>


</shape>
 <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me"
        android:clickable="true"
        android:background="@drawable/drawable_button_selector"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 private fun initLayout() {
        button.setOnClickListener {
            it.isSelected = !it.isSelected
            Log.d("Click Me", "Button isSelected" + it.isSelected)
            Toast.makeText(this, "Button Clicked and isSelected = " + it.isSelected, Toast.LENGTH_SHORT).show()

        }