java - android - 自定义按钮(使用选择器文件)不起作用
问题描述
我正在尝试创建一个“添加到收藏夹”按钮。
问题是除非我一直按下按钮,否则drawable不会改变。一旦我释放按钮,它就会返回到原来的drawable。
我遵循了本教程:https ://www.youtube.com/watch?v=Nn4-Vn7qk9k但得到了不同的结果。
我创建了一个 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
drawable_button_selector.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>
drawable_button_selected.xml
<?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
drawable_button_unselected.xml
<?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()
}
推荐阅读
- groovy - 如何在 TestHttpClient 中设置 POST 参数
- docusignapi - 尝试获取信封状态或文档时的 USER_DOES_NOT_BELONG_TO_SPECIFIED_ACCOUNT
- c++ - 如果系统磁盘在 Windows 2016 中是动态的,则系统保留分区和卷“C:\”具有相同的唯一 ID
- asp.net - 使用 Ajax 请求在 MVC 中上传 Excel 文件
- c# - datagrid wpf的特定动态列的上下文菜单
- excel - With函数中的多个对象表达式遍历所有工作表
- linux - 用其他字符串替换多个给定字符串
- python - bash 从一列中聚类数据并从另一列中提取其值
- java - 子级更新时未在父级中更新乐观锁定版本
- windows - CMake 发现 ImageMagick 在 Windows 上不起作用