我的问题是,我想在一个
RecyclerView
中选择一个项目,它应该改变颜色,如果我点击另一个项目,第一个被选中的项目应该改变为默认颜色(最后一个被点击的项目应该有被选中的颜色)。
我已经改变了所选项目的颜色,如果我再次点击所选项目,它就会变成默认颜色。现在我只想知道,如果我点击一个未选择的项目,如果我已经选择了一个项目,它们的颜色就会 "切换"。
这是我的SubItem类。
class SubItem(val channel: Channel) : Item<GroupieViewHolder>() {
@SuppressLint("ResourceAsColor")
override fun bind(viewHolder: GroupieViewHolder, position: Int) {
val profileImageUrl = channel.channel_logo
viewHolder.itemView.sub_item_name.text = channel.channel_name
viewHolder.itemView.sub_item_layout.setBackgroundResource(R.color.white)
viewHolder.itemView.sub_item_name.setTextColor(R.color.colorSecondaryText)
val targetImageView = viewHolder.itemView.sub_item_profile
try {
Picasso.get().load(profileImageUrl)
.placeholder(R.drawable.ic_baseline_account_circle_24)
.into(targetImageView)
}catch (e:Exception){
Log.d("SubItem","${e.message}")
viewHolder.itemView.sub_item_layout.setOnClickListener {
if (selected_position == position){
selected_position = null
viewHolder.itemView.sub_item_layout.setBackgroundResource(R.color.white)
viewHolder.itemView.sub_item_name.setTextColor(R.color.colorSecondaryText)
else{
selected_position = position
viewHolder.itemView.sub_item_layout.setBackgroundResource(R.color.colorSecondaryText)
viewHolder.itemView.sub_item_name.setTextColor(R.color.black)
override fun getLayout(): Int {
return R.layout.subscription_item
如果有帮助的话,这是我的函数,我把项目添加到RecyclerView
中。
private fun fetchSubs() {
val uid = auth.uid
val user = database.getReference("/users/$uid/subscriptions")
val adapter = GroupAdapter<GroupieViewHolder>()
user.addListenerForSingleValueEvent(object : ValueEventListener{
@SuppressLint("NotifyDataSetChanged")
override fun onDataChange(p0: DataSnapshot) {
p0.children.forEach{
val sub = it.getValue(Subscription::class.java) ?: return
if (sub.subscribed == true) {
val ref = database.getReference("/channels/${sub.channel_uid}")
ref.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
val channel = p0.getValue(Channel::class.java) ?: return
adapter.add(SubItem(channel))
override fun onCancelled(error: DatabaseError) {
adapter.setOnItemClickListener{ item, view ->
val subItem = item as SubItem
val channelName = subItem.channel.channel_name
val channelUid = subItem.channel.uid
Toast.makeText(requireContext(),"$channelName : $channelUid", Toast.LENGTH_SHORT).show()
fetchSubs()
sub_recyclerview.adapter = adapter
override fun onCancelled(error: DatabaseError) {
对不起,我没有使用模型和适配器