1

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

But my problem is after clicking for example on the 2th item,the 10st item also gets selected.Likewise after clicking my 5th item the 3nd item is selected.

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

masood
  • 725
  • 8
  • 23

2 Answers2

2

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 - 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 - 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 - create data class(Based on the data you want to bind in RecyclerView) as bellow

My Model(UserModel.kt)

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

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

    }

}  

I hope you find it useful

masood
  • 725
  • 8
  • 23
-1

You have to set color for other items when you cal