【问题标题】:Kotlin Recyclerview row item selection background color changeKotlin Recyclerview 行项目选择背景颜色变化
【发布时间】:2020-08-17 20:55:35
【问题描述】:

我可以在我的recyclerview 中更改text 的颜色和点击我的recyclerview 的行的背景。

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

我该如何解决这个问题?
实际上我的问题是如何更改在 Kotlin 中点击它的 recyclerview 项目的背景颜色? 我还按照this link 中的说明进行操作。但它没有正常工作!!

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
    )

activity_main_page.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>

请帮帮我
谢谢

【问题讨论】:

    标签: android android-recyclerview


    【解决方案1】:

    在网上彻底搜索后,我终于能够解决这个问题。
    我一步一步放代码,如果需要的话会给出解释。

    1 - 创建新的 android studio 项目
    2 - activity_main.xml 的编码如下:
    activity_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 - 为 recycler 视图行(项目)创建一个布局,名称为 item_list.xml,如下所示
    item_list.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 创建适配器,如下所示

    CustomAdapter.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)
            }
    
        }
    
    }  
    

    希望对你有用

    【讨论】:

      【解决方案2】:

      你需要在校准时为其他项目设置颜色

      【讨论】:

      • 您的回答不完整。尝试发布可读且有助于解决问题的答案
      • 不明白什么意思?
      猜你喜欢
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      相关资源
      最近更新 更多