Kotlin Recyclerview行项目选择背景颜色变化

2023-11-29

我能够改变的颜色text和点击我的行的背景recyclerview in my recyclerview.

但我的问题是,例如单击第二个项目后,第 10 个项目也会被选中。同样,单击第 5 个项目后,第 3 个项目也会被选中。

我该如何解决这个问题?
事实上,我的问题是如何更改单击它的 recyclerview 项目的背景颜色Kotlin? 我也按照中的说明进行操作这个链接。但它没有正确工作!

AllChanelAdapter.kt

class AllChanelAdapter(private val datalist:MutableList<AllChanelModel>, var clickListener: OnItemClickListener):RecyclerView.Adapter<AllChanelHolder>() {
    private lateinit var context:Context
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AllChanelHolder {
        context = parent.context
        return AllChanelHolder(LayoutInflater.from(context).inflate(R.layout.allchanel_singleitem,parent,false))
    }
    override fun getItemCount(): Int = datalist.size

    override fun onBindViewHolder(holder: AllChanelHolder, position: Int) {
        val data = datalist[position]
        val txt_title = holder.itemView.txt_title
        val txt_body = holder.itemView.txt_body
        val img_chanel = holder.itemView.img_chanel

        txt_title.setText(data.title)
        txt_body.setText(data.body)

        Glide
            .with(context)
            .load("...")
            .centerCrop()
            .into(img_chanel);
    }
    holder.initialize(datalist.get(position),clickListener)
}
interface OnItemClickListener {
    fun onItemClick(item: AllChanelModel, position: Int, view: View)
}

AllChanelHolder.kt

class AllChanelHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    fun initialize(item:AllChanelModel,action:OnItemClickListener){
        itemView.setOnClickListener {
            action.onItemClick(item,adapterPosition,itemView)
        }
    }
}  

MainPageActivity.kt

class MainPageActivity : AppCompatActivity(),OnItemClickListener {

    private val datalist:MutableList<AllChanelModel> = mutableListOf()
    lateinit var allchaneladapter : AllChanelAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_page)
        
        send_request()

        allchaneladapter = AllChanelAdapter(datalist,this)
        all_chanel_recycler.layoutManager = LinearLayoutManager(this)
        all_chanel_recycler.adapter = allchaneladapter
    }

    private fun send_request(){
        val url = "http://10.0.2.2:8000/getsamplejson" // localhost api
        val que = Volley.newRequestQueue(this@MainPageActivity)
        val req = JsonArrayRequest(Request.Method.GET,url,null,
            Response.Listener {
                response->
                for(i in 0..response.length()-1){
                    var chanel_obj = response.getJSONObject(i)
                    datalist.add(
                        AllChanelModel(
                            chanel_obj.getString("body"),
                            chanel_obj.getString("title"),
                            chanel_obj.getString("userId")
                        )
                    )
                }
                allchaneladapter.notifyDataSetChanged()
            }, Response.ErrorListener {
                error->
                   Log.e("",error.message)
            })

            que.add(req)
    }
    override fun onItemClick(item: AllChanelModel, position: Int, view: View) {
        view.setBackgroundColor(Color.YELLOW)
    }
}    

AllChanelModel.kt

data class AllChanelModel(
    @SerializedName("body")
    val body: String,
    @SerializedName("title")
    val title: String,
    @SerializedName("userId")
    val userId: String
    )

活动_主_页面.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainPageActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/all_chanel_recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

allchanel_singleitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/linear_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:orientation="vertical"
        android:padding="5dp">

        <TextView
            android:id="@+id/txt_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:text="TextView"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/txt_body"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center|right"
            android:text="TextView"
            android:textColor="#000000" />

    </LinearLayout>

    <ImageView
        android:id="@+id/img_chanel"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_weight="1"
        app:srcCompat="@mipmap/ic_launcher" />

</LinearLayout>

请帮我
谢谢


经过网上的彻底搜索,终于能够解决这个问题。
我一步一步地给出了代码,并在需要时给出解释。

1 - 创建新的android studio项目
2 - Activity_main.xml 的代码如下:
活动_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainPageActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:drawable/screen_background_light_transparent"
        tools:listitem="@layout/item_list" />
</androidx.constraintlayout.widget.ConstraintLayout>  

3 - 为 recyclerview 行(项目)创建一个名为 item_list.xml 的布局,如下所示
项目列表.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/linear_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:background="#FFFFFF"
        android:orientation="vertical"
        android:padding="5dp">

        <TextView
            android:id="@+id/tv_label"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:text="TextView"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center|right"
            android:text="TextView"
            android:textColor="#000000" />

    </LinearLayout>

    <ImageView
        android:id="@+id/img_chanel"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_weight="1"
        app:srcCompat="@mipmap/ic_launcher" />

</LinearLayout>  

4 - 创建数据类(基于要在 RecyclerView 中绑定的数据),如下所示

我的模型(UserModel.kt)

    public data class UserModel(var title:String,var name:String,var isSelected:Boolean=false) 

5 - 为您的 RecyclerView 创建适配器,如下所示

自定义适配器.kt

class CustomAdapter(private val context: Context, private val list: ArrayList<UserModel>,
private val listener: OnItemClickListener
                    ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private inner class ViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView),View.OnClickListener {

        internal var tvLabel: TextView
        internal var tvName: TextView

        init {
            tvLabel = itemView.findViewById(R.id.tv_label) // Initialize your All views prensent in list items
            tvName = itemView.findViewById(R.id.tv_name) // Initialize your All views prensent in list items
            itemView.setOnClickListener(this)
        }

        internal fun bind(position: Int) {
            // This method will be called anytime a list item is created or update its data
            //Do your stuff here
            tvLabel.text = list[position].title
            tvName.text = list[position].name
        }

        override fun onClick(v: View?) {
            val position:Int = adapterPosition
            if(position != RecyclerView.NO_POSITION) {
                listener.onItemClick(position,this@CustomAdapter,itemView)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_list, parent, false))
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if(list[position].isSelected){
            holder.itemView.setBackgroundColor(Color.YELLOW)
            holder.itemView.findViewById<LinearLayout>(R.id.linear_content).setBackgroundColor(Color.YELLOW)
        } else{
            holder.itemView.setBackgroundColor(Color.WHITE)
            holder.itemView.findViewById<LinearLayout>(R.id.linear_content).setBackgroundColor(Color.WHITE)
        }
        (holder as ViewHolder).bind(position)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    interface OnItemClickListener{
        fun onItemClick(position: Int,adapter:CustomAdapter,v:View)
    }
}  

6 - MainActivity.kt 的代码如下:
MainActivity.kt

class MainActivity : AppCompatActivity(),CustomAdapter.OnItemClickListener {
    private val data = arrayListOf<UserModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_page)

        val recyclerview = findViewById<RecyclerView>(R.id.recycler_view)

        data.add(UserModel(title = "item 1",name = "name 1"))
        data.add(UserModel(title = "item 2",name = "name 2"))
        data.add(UserModel(title = "item 3",name = "name 3"))
        data.add(UserModel(title = "item 4",name = "name 4"))
        data.add(UserModel(title = "item 5",name = "name 5"))
        data.add(UserModel(title = "item 6",name = "name 6"))
        data.add(UserModel(title = "item 1",name = "name 1"))
        data.add(UserModel(title = "item 2",name = "name 2"))
        data.add(UserModel(title = "item 3",name = "name 3"))
        data.add(UserModel(title = "item 4",name = "name 4"))
        data.add(UserModel(title = "item 5",name = "name 5"))
        data.add(UserModel(title = "item 6",name = "name 6"))
 

        val adapter = CustomAdapter(this,data,this)
        recyclerview.layoutManager = LinearLayoutManager(this)
        recyclerview.adapter = adapter
        recyclerview.setHasFixedSize(true)

    }


    override fun onItemClick(position: Int,adapter: CustomAdapter,v:View) {
        val clicked_item:UserModel = data[position]
        clicked_item.title = "clicked"
        clicked_item.isSelected = !clicked_item.isSelected
        if(clicked_item.isSelected){
            recycler_view.getChildAt(recycler_view.indexOfChild(v)).setBackgroundColor(Color.YELLOW)
            recycler_view.getChildAt(recycler_view.indexOfChild(v)).findViewById<LinearLayout>(R.id.linear_content).setBackgroundColor(Color.YELLOW)
        }else{
            recycler_view.getChildAt(recycler_view.indexOfChild(v)).setBackgroundColor(Color.WHITE)
            recycler_view.getChildAt(recycler_view.indexOfChild(v)).findViewById<LinearLayout>(R.id.linear_content).setBackgroundColor(Color.WHITE)
        }

    }

}  

希望对你有帮助

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Kotlin Recyclerview行项目选择背景颜色变化 的相关文章

  • 服务如何在后台运行 - Android

    今天的采访中我被问到了这个问题 什么是服务 我对此的回答是 Service 是 Android 的基本组件 它没有 UI 并且在后台运行 Service 是否在主线程上运行 不 那么它是如何在后台运行的呢 我心里一片空白 有人可以解释一下如
  • 将用户重定向到 iTunes 应用商店或 Google Play 商店?

    我正在寻找一种简单的解决方案来发布我的应用程序的一个链接 例如在 Facebook 上 如果用户使用移动设备访问它 它应该自动重定向到正确的应用程序商店 否则 用户应该被重定向到我的网站 iOS应用程序 http itunes apple
  • Android Widget ID 是否持久

    在从桌面删除该 Widget 实例之前 您从操作系统收到的用户桌面上特定 Widget 实例的 Widget ID 是否一致 我找不到任何明确说明这一点的文档 但我假设这是因为文档说您可以使用小部件 id 来存储任何实例配置信息 我想将一些
  • 配置项目 ':react-native-gesture-handler' 时出现问题

    大家好 我已经尝试了很长时间来解决这个问题 但不幸的是我还没有弄清楚如何解决 希望你们能帮助我 所以我有一个反应本机项目和我的朋友 以及我的一位朋友添加 React native gesture handler 包供我们使用 他对这个包没有
  • 需要对某些片段禁用 CollapsingToolbarLayout 的展开

    我有一个AppCompatActivity控制替换许多片段 这是我的布局 活动 main xml
  • 如何以编程方式判断蓝牙设备是否已连接?

    我了解如何获取已配对设备的列表 但如何判断它们是否已连接 这一定是可能的 因为我看到它们列在我手机的蓝牙设备列表中 并且它说明了它们的连接状态 将蓝牙权限添加到您的AndroidManifest中
  • 如何使用具有三种布局的视图翻转器?

    我目前正在使用ViewFlipper我的主要活动有两种不同的布局 我想使用第三种布局 但我只能找到showNext and showPrevious 命令 有人可以告诉我如何使用来实现第三种布局吗ViewFlipper 为您制作了一个示例
  • 如何使用retrofit2动态设置超时?

    public class Router private static Retrofit retrofit null public Retrofit getRetrofit if retrofit null OkHttpClient clie
  • 在 Android 市场中以编程方式检查我的应用程序版本

    目前 我正在启动时检查应用程序版本代码 并将其与我的服务器上的最新版本代码进行匹配 并根据此匹配 我发送用户从 Android 市场获取最新更新 它运行良好 但我的问题是我必须手动更改服务器上的最新版本代码 并且我不知道新版本何时发布APK
  • Android 中图像字节表示的每像素字节数

    我目前正在编写一个Android应用程序 需要在其中使用OCR 为了实现这一点 我将 Tesseract 与tesseract android tools 项目 http code google com p tesseract androi
  • 如何在 Android 中创建始终位于顶部的全屏覆盖 Activity

    我希望能够创建一个始终位于 Android 显示前面的 Activity 它不应该接收任何输入 只需将其传递到其下面的任何应用程序即可 像平视显示器之类的东西 我能够研究我需要将底层窗口类型设置为 TYPE SYSTEM ALERT 但看起
  • 无法接收UsbManager.ACTION_USB_DEVICE_ATTACHED/UsbManager.ACTION_USB_DEVICE_DETACHED的广播Intent

    我最近正在编写一个 USB 主机应用程序 但它被卡住了 因为我无法检测到设备连接 分离事件 我遵循了编码说明http developer android com guide topics connectivity usb host html
  • 如何连接到Google Play服务并加载排行榜

    我想将我的游戏与 Google Play 服务连接 我已阅读有关 Android 开发人员的文档 并尝试遵循输入数字示例 但仍然无法加载排行榜 我有导入baseGameUtils 但我使用andengine 所以我没有使用来自谷歌的exte
  • 在 Android 中使用 AES 加密的最佳实践是什么?

    我为什么问这个问题 我知道人们对 AES 加密存在很多疑问 即使对于 Android 也是如此 如果您在网络上搜索 会发现很多代码片段 但在每个页面上 在每个 Stack Overflow 问题中 我都发现了另一个具有重大差异的实现 所以我
  • 如何从画布中删除路径区域(Android)

    我需要裁剪角落ImageView 不要将它们弄圆 而是擦除每个角上的三角形 似乎唯一的方法就是覆盖onDraw方法并使用从画布上删除这些区域Path 问题是我没有纯色背景 所以我需要擦除这些区域 但不要用某种颜色填充它们 我为此使用以下代码
  • 旋转 Google 地图中的两层标记图标

    在我的应用程序中 我向地图添加了一定数量的标记 如下所示 private fun addMarker googleMap GoogleMap location Location val options MarkerOptions optio
  • 如何让surfaceview透明

    大家好 我想让我的 DrawingSurface 视图透明 我尝试了很多东西 但它不起作用 这是我的 xml 代码 使我的表面视图透明
  • 活动中列表视图中的粘滞行

    我的列表视图中只有一行应该是粘性的 而不是粘性标题中带有字母的部分或部分 我真的很感激任何关于列表视图在活动中粘性一行而不是片段的帮助 我该怎么做 我真的很感谢任何帮助 提前致谢 使用如下代码 class MyAsyncTask exten
  • 在 VideoView 开始播放之前,TextView 不会显示

    我编写了一个android应用程序 它有两个视图 TextView上方的VideoView 位于ScrollView内部 我遇到了一个问题 直到VideoView开始播放视频 TextView才显示 并且我有一个黑屏 这可能需要很长一段时间
  • FCM 主题是否适合更多用户?

    我对使用主题消息有点困惑 我的场景是根据通知触发一些作业 请帮助我更多地了解这一点 如果我们正在处理大量用户 则可以使用 FCM 主题向用户发送通知 我们可以只使用数据消息和主题消息吗 使用主题发送的消息是否保证送达 我在 FCM 文档中看

随机推荐