添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
微醺的豌豆  ·  error: ‘string’ in ...·  3 月前    · 
善良的红茶  ·  python ...·  1 年前    · 
听话的伤痕  ·  Inno Setup ...·  1 年前    · 

改变RecyclerView中未选择/选中的项目的颜色

0 人关注

我的问题是,我想在一个 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) {

对不起,我没有使用模型和适配器

5 个评论
你所写的逻辑只有在用户点击项目时才起作用。你必须在onClick之外编写颜色设置逻辑,以便在滚动时将正确的颜色添加到项目中。
@AshutoshOjha 如果我写了。 if (selected_position == position)} viewHolder.itemView.sub_item_layout.setBackgroundResource(R.color.colorSecondaryText) viewHolder.itemView.sub_item_name.setTextColor(R.color.black)} else{ viewHolder.itemView.sub_item_layout.setBackgroundResource(R.color.white) viewHolder.itemView.sub_item_name.setTextColor(R.color.colorSecondaryText)} 在clickListener下,它也不工作。
在设置完选定的位置后,呼叫通知数据变化
@AshutoshOjha 如果你的意思是在 if else 之后的clickListener中添加 notifyChanged 。然后在clickListener下面加上我上面评论的代码。不幸的是,在寻求帮助之前,我已经试过了,但没有效果。
在列表中添加一个布尔值isSelected,并在点击时更新列表中的这个布尔值,并调用notifyChange(),在if(list.get(position).isSelected)上应用你的逻辑。
android
kotlin
android-recyclerview
groupie
Andrey
Andrey
发布于 2022-09-14
1 个回答
Andrey
Andrey
发布于 2022-09-16
已采纳
0 人赞同

For everyone who uses groupie like me this could help you in future.

This is my solution for my Problem.

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
        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}")
//            Toast.makeText(,e.message,Toast.LENGTH_SHORT).show()
        checkFilter(viewHolder,position)
    @SuppressLint("ResourceAsColor")
    private fun checkFilter(v: GroupieViewHolder, p: Int) {
        when (SubscriptionsFragment.list[p]) {
            true -> {
                v.itemView.sub_item_layout.setBackgroundResource(R.color.colorDivider)
                v.itemView.sub_item_name.setTextColor(R.color.black)
            false -> {
                v.itemView.sub_item_layout.setBackgroundResource(R.color.white)
                v.itemView.sub_item_name.setTextColor(R.color.colorSecondaryText)
    override fun getLayout(): Int {
        return R.layout.subscription_item

My function with setOnItemClickListener

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) {
                list = mutableListOf()
                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
                                list.add(false) // created in companion object: var list =  mutableListOf<Boolean>()
                                oldList.add(false) // created in companion object: var oldlist =  mutableListOf<Boolean>()
                                adapter.add(SubItem(channel))
                            override fun onCancelled(error: DatabaseError) {
                adapter.setOnItemClickListener{ item, view ->
                    val subItem = item as SubItem
                    val pos = adapter.getAdapterPosition(subItem)
                    // Here happens the magic
                    list[pos] = !list[pos] // change selected item from false to true or from true to false
                    val l = list[pos] // saving Boolean
                    list = mutableListOf()
                    oldList.forEach{ // using oldList to loop so many times I need
                        list.add(false) // setting all to false
                    if (l){ // if Boolean is true
                        list[pos] = !list[pos] // change selected item from false to true
                    val channelUid = subItem.channel.uid
                    fetchVideos(channelUid)
                    adapter.notifyDataSetChanged() // refresh all items in SubItem
                try {
                    sub_recyclerview.adapter = adapter
                } catch(e:Exception){
                    Log.d("fetchSubs","${e.message}")
            override fun onCancelled(error: DatabaseError) {