Kotlin Recyclerview行项目选择背景颜色更改 [英] Kotlin Recyclerview row item selection background color change

查看:337
本文介绍了Kotlin Recyclerview行项目选择背景颜色更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以更改text的颜色和recyclerview中单击的recyclerview行的背景.

I am able to change the color of the text and background of row clicked of my recyclerview in my recyclerview.

但是我的问题是,例如在单击第二项后,也会选择第十项.同样,在单击第五项后,也会选择第三项.

我该如何解决?
实际上,我的问题是,如何更改在科特林中单击的recyclerview项目的背景颜色? 我还按照此链接中的说明进行操作.但是它不能正常工作!

How do i solve this?
in fact my question is that how to change background color of recyclerview item that click on it in Kotlin? I also followed the instructions in this link. But it did not worked correctly!!

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>

请帮助我
谢谢

please help me
thank you

推荐答案

在Internet上进行了彻底的搜索之后,我终于能够解决此问题.
我逐步编写了代码,并在需要时提供了解释.

After a thorough search on the Internet, I was finally able to solve this problem.
I put the code step by step and give explanations if needed.

1-创建新的android studio项目
2-activity_main.xml的编码如下:
activity_main.xml

1 - create new android studio project
2 - cods for activity_main.xml as below:
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-为名称为item_list.xml的波纹管回收器视图行(项目)创建布局
item_list.xml

3 - create a layout for recycler view row(item) with name item_list.xml as bellow
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中绑定的数据)

4 - create data class(Based on the data you want to bind in RecyclerView) as bellow

我的模型(UserModel.kt)

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

5-为下面的RecyclerView创建适配器

5 - create Adapter for your RecyclerView as bellow

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

6 - codes for MainActivity.kt as bellow:
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)
        }

    }

}  

我希望您觉得它有用

这篇关于Kotlin Recyclerview行项目选择背景颜色更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆