javaandroidkotlinandroid-recyclerviewnestedrecyclerview

How to Modify Only First Nested RecyclerView (child) element at Position 0 of Parent RecyclerView?


I have parentRecyclerview that includes a nestedRecyclerview. nestedRecyclerView lists several items: (Apple, Banana, Pear). I want to bold the first item (apple) of this nestedRecyclerview like so:

**Apple**
Banana
Pear

-------

Apple
Banana
Pear

-------

Apple
Banana
Pear

I can get it to bold the first item of each nested recyclerview list by doing:

when (position) {
0 -> 
// code to make apple bold
}

but that gives me:

**Apple**
Banana
Pear

-------

**Apple**
Banana
Pear

-------

**Appla**
Banana
Pear

How do I go about this? I would add all my code, but honestly it is a ton of code and much more complex that apples, bananas, pears. I prefer code in Kotlin, but I can figure out Java if thats what you know. Thanks!

Lots of internet searching done, but most talk about onClickListener events.


Solution

  • try using this create variable to manage bold of view based on position

    class NestedAdapter(...) {
    private var topItemBold = false
    
    override fun onBindViewHolder(holder: NestedViewHolder, position: Int) {
        val item = items[position]
    
        if (topItemBold && position == 0) {
            holder.textView.setTypeface(null, Typeface.BOLD)
        } else {
            holder.textView.setTypeface(null, Typeface.NORMAL)
        }
    
        // ... rest of your binding logic
    }
    

    and update your parent adapter like this

    class ParentAdapter(...) {
    override fun onBindViewHolder(holder: ParentViewHolder, position: Int) {
    
        val nestedAdapter = holder.nestedRecyclerView.adapter as NestedAdapter
    
        if (position == 0) {
            nestedAdapter.topItemBold = true
        } else {
            nestedAdapter.topItemBold = false
        }
    }
    

    so in above our topItemBold only true for first item on nested view on first item of parent list