Home > Back-end >  How can I change or replace layout on the right by clicking on a recycleview item on the left same p
How can I change or replace layout on the right by clicking on a recycleview item on the left same p

Time:08-16

I have a layout that is divided into two, the RecyleView on the left and the details on the right. I would like that when I click an item on the left the layout on the right is replace based on the item clicked. Can someone help me achieve this, or help with a better approach to this. Thank you

Sample image of what I would like

CodePudding user response:

You can try this simple solution, use interface.

In your adapter create a interface which is used for implement onClick in your item. Then, call it in onBindViewHolder. For example:

class YourAdapter(val onclick: OnClickListener): RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    interface OnClickListener {

        fun onClickItem(position: Int)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        holder.itemView.setOnClickListener {
                onclick.onClickItem(position) // Here i will pass position for Ex, you can pass anything you want depend on 
                                              //  what's your declared in parameter of onClickItem function
            }
    }

Declare adapter and implement interface in your Activity.

class YourActivity() : YourAdapter.OnClickListener() {

    lateinit var adapter: YourAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        adapter = YourAdapter(this)
    }

    override fun onClickItem(position: Int) {
        // now you can set content to the view on the right, i've pass position item of recyclerView over here. 
        // content will change based on item you click on the left. 
        // Ex, i have a TextView on the right.
        myTextview.settext(position.toString())
    }
}
  • Related