AppCompatButton使用background selector点击后边框短暂消失问题排查
问题根因
- 点击后状态未持久化:你在selector中配置了
state_selected、state_activated状态下的边框样式,但点击事件中仅处理了业务回调,没有主动给按钮设置选中状态。松手后state_pressed临时状态失效,自动切回未选中样式,就出现了边框只显示1秒的现象。 - 缺少RecyclerView选中状态管理:RecyclerView的item会复用,若不全局记录选中位置、绑定状态到item,后续滚动列表时选中状态也会出现错乱。
修复步骤
1. Adapter新增选中位置记录
在Adapter中新增变量存储当前选中的位置,默认值可根据业务需求设置为-1(默认无选中)或0(默认选中第一项):
class ilmcategoriesAdapter(var countryList: List<ilmcategoriesData>, var activity: MainActivity, var listener: OnClickRecyclerChild): RecyclerView.Adapter<ilmcategoriesAdapter.ViewHolder>(){ // 新增全局变量,记录当前选中的item位置 var selectedPosition: Int = -1 // 原有代码不变... }
2. 绑定选中状态到item
在onBindViewHolder中根据当前位置和选中位置的匹配关系,给按钮设置选中状态,同时点击时更新选中位置并刷新列表:
override fun onBindViewHolder(holder: ilmcategoriesAdapter.ViewHolder, position: Int) { val currentItem = countryList[position] holder.eventName.text = currentItem.name // 给按钮设置选中状态 holder.eventName.isSelected = position == selectedPosition holder.eventName.setOnClickListener { // 更新选中位置 selectedPosition = position // 刷新列表同步所有item的状态 notifyDataSetChanged() // 原有业务逻辑不变 val categoryID = currentItem.id val categoryIdStr = categoryID.toString() AppPreferences.heightInCentimeters = categoryID listener.myCallback(categoryIdStr) } }
3. 可选:优化selector冗余状态
如果不需要按压、聚焦状态和选中状态共用同一样式,可以简化selector,避免状态冲突:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 选中状态 --> <item android:state_selected="true" android:drawable="@drawable/transparent_bg_bordered_button_default"/> <!-- 未选中状态 --> <item android:drawable="@drawable/transparent_bg_bordered"/> </selector>
注:你布局中声明的是
AppCompatButton,ViewHolder中用TextView接收是可以正常运行的,因为AppCompatButton是TextView的子类,无需额外修改。
内容的提问来源于stack exchange,提问作者Enigma
相关产品推荐
相关产品推荐

