Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display item info on selected item in RecyclerView using Kotlin

How to display some information from recyclerview selected item without using onClick method. When the app is started first item is selected and highlighted. I need to eg. use Toast with value of anything that is in data class. I have implemented onClick method but the question is how to do it without using this method.

This is MainActivity:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        val exampleList = generateDummyList(20)
        val exampleAdapter = ExampleAdapter(getItem, exampleList)

        exampleAdapter.onItemClick = { item, position: Int ->
            Toast.makeText(this, "Position: $position", Toast.LENGTH_SHORT).show() 
            val intent = Intent(this, ItemActivity::class.java).apply {
                putExtra("itempos", position)
                putExtra("maxSize", maxS)
            }
            startActivity(intent)
        }
    }
}

This is adapter:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class ExampleAdapter(val chosen_item: Int, private val exampleList: List<ExampleItem>):
RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder>()
{
    var onItemClick: ((ExampleItem, Int) -> Unit)? = null    
    var selected_item: Int = chosen_item
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_recy, parent, false)
        return ExampleViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ExampleViewHolder, position: Int){
        val currentItem = exampleList[position]
        holder.tv_ID.text = currentItem.id.toString()
        holder.tv_NAME.text = currentItem.name
        holder.tv_EMAIL.text = currentItem.email
        if (position == selected_item){
            holder.tv_NAME.setBackgroundColor(Color.GREEN)            
        } else {
            holder.tv_NAME.setBackgroundColor(Color.TRANSPARENT)            
        } 
}
override fun getItemCount(): Int {
        return exampleList.size
    }
    inner class ExampleViewHolder(itemView:View): RecyclerView.ViewHolder(itemView) {
        val tv_ID: TextView = itemView.tv_ID
        val tv_NAME: TextView = itemView.tv_NAME
        val tv_EMAIL: TextView = itemView.tv_EMAIL
    init {
            itemView.setOnClickListener{
                onItemClick?.invoke(exampleList[absoluteAdapterPosition], absoluteAdapterPosition)
                notifyItemChanged(selected_item)
                selected_item = absoluteAdapterPosition
                notifyItemChanged(selected_item)                
            }            
            itemView.isSelected
        }
    }
}

I have second activity – when user click on item in first activity(recyclerview) – this second activity is open – then I raise the id of item by one and open again first activity where another item is highlighted. And I need to display eg. EMAIL from ExampleItem class.

This is second activity:

class ItemActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_item)
        var itempos = intent.getIntExtra("itempos",0)
        val maxSize = intent.getIntExtra("maxSize",0)
        button2.setOnClickListener {
            if (itempos == maxSize){
                itempos = itempos
            } else {
                itempos = itempos + 1
            }
            val intent = Intent(this, MainActivity::class.java).apply {
                putExtra("itemposplus", itempos)
            }
            startActivity(intent)
        }
    }
}

>Solution :

If I understood correctly, you want to get the selected item at any time (without a click). There are several ways to do this. I recommend updating your selected_item variable inside the onBindViewHolder method based on position.

override fun onBindViewHolder(holder: ExampleViewHolder, position: Int){
        selected_item = position
        ...

And then write a public method into the adapter for get the current item in activity

fun getCurrentItem() = exampleList.get(selected_item)

Finally you can get selected item in activity

val selectedItem = exampleAdapter.getCurrentItem()

When the viewHolder bound, selected_item will update due to the current selected. And then you can get the selected item without any triggers.
Also check the getAdapterPosition() method in your ViewHolder or
getLayoutManager().findFirstVisibleItemPosition() method in your RecyclerView

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading