我有一个
recyclerview
有一排按钮。我的目标是使当前选定的按钮的文本为青色,而其他按钮的文本为灰色。
为此,我在
TabAdapter
班级:
class TabAdapter(private val items: ArrayList<Pair<String, ArrayList<String>>>, private val context: Context) : RecyclerView.Adapter<TabViewHolder>() {
private var selectedPosition: Int = RecyclerView.NO_POSITION
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TabViewHolder {
return TabViewHolder(LayoutInflater.from(context).inflate(R.layout.tabrecycler_item_column, parent, false))
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: TabViewHolder, position: Int) {
context as AnimeFaceKeyboard
holder.itemView.isSelected = selectedPosition == position
if (holder.itemView.isSelected) {
holder.button.setTextColor(ContextCompat.getColor(context, R.color.material_deep_teal_200))
} else {
holder.button.setTextColor(ContextCompat.getColor(context, R.color.material_grey_600))
}
//This code sets the widths of the buttons to, at minimum,
//occupy the entire width of the screen combined
val displayMetrics = Resources.getSystem().displayMetrics
if (itemCount * (120 * displayMetrics.density) < displayMetrics.widthPixels) {
holder.button.width = displayMetrics.widthPixels / itemCount
}
holder.button.text = items[position].first
holder.button.setOnClickListener {
//TODO - Figure out how this code works
notifyItemChanged(selectedPosition)
selectedPosition = holder.layoutPosition
notifyItemChanged(selectedPosition)
//This code updates a different recyclerview.
context.isFavoritesTabSelected = position == items.lastIndex
context.updateCurrentImageLayout(items[position].second)
}
}
}
class TabViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val button: Button = view.tabButton
}
相关线路在
onBindViewHolder
方法。特别是这条线
holder.itemView.isSelected = selectedPosition == position
这段代码在
onClick
按钮的方法
notifyItemChanged(selectedPosition)
selectedPosition = holder.layoutPosition
notifyItemChanged(selectedPosition)
下面是
回收视图
:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<Button
android:id="@+id/tabButton"
android:layout_width="match_parent"
android:minWidth="120dp"
android:layout_height="match_parent"
android:text="Unset-Button-Text"
android:background="@color/darkshade"
style="@style/Widget.AppCompat.Button.Borderless"/>
</android.support.constraint.ConstraintLayout>
我的行为
recyclerView
是部分功能。当前选定按钮的文本,实际上是青色的。
但是,有两个问题
1]点击按钮时,按钮部分变为透明。点击涟漪动画一定有问题
和
2]涟漪动画只应为选定的当前按钮播放,但也会为先前选定的按钮播放。
以下是我手机上的gif演示: