RecyclerView itemClickListener in Kotlin

2019-01-09 09:34发布

问题:

I'm writing my first app in Kotlin after 3 years of experience with Android. Just confused as to how to utilize itemClickListener with a RecyclerView in Kotlin.

I have tried the trait (edit: now interface) approach, very Java-like

public class MainActivity : ActionBarActivity() {

  protected override fun onCreate(savedInstanceState: Bundle?) {

    // set content view etc go above this line

    class itemClickListener : ItemClickListener {
      override fun onItemClick(view: View, position: Int) {
        Toast.makeText(this@MainActivity, "TEST: " + position, Toast.LENGTH_SHORT).show()
      }
    }

    val adapter = DrawerAdapter(itemClickListener())
    mRecyclerView.setAdapter(adapter)
 }

  trait ItemClickListener {
    fun onItemClick(view: View, position: Int)
  }
}

That seemed very redundant so I tried the inner class approach:

inner class ItemClickListener {
    fun onItemClick(view: View, position: Int) {
        startActivityFromFragmentForResult<SelectExerciseActivity>(SELECT_EXERCISES)
    }
}

And then just setting the adapter's click listener like this:

val adapter = WorkoutsAdapter(ItemClickListener())

But I'm still not satisfied with this because I think there might be a better, cleaner way. I'm trying to essentially achieve something like this: RecyclerView onClick

Any suggestions?

Ended up going with a variation of the approved answer

Defined the function in the activity:

val itemOnClick: (View, Int, Int) -> Unit = { view, position, type ->
    Log.d(TAG, "test")
}

Passed the function itself on to the adapter like this:

class ExercisesAdapter(val itemClickListener: (View, Int, Int) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
      // other stuff up here
      val vhExercise = ExerciseVH(view) // view holder
      // on to the view holder through the extension function
      vhExercise.onClick(itemClickListener)
    }
}

Extension function by Loop in the approved answer below.

fun <T : RecyclerView.ViewHolder> T.onClick(event: (view: View, position: Int, type: Int) -> Unit): T {
    itemView.setOnClickListener {
        event.invoke(it, getAdapterPosition(), getItemViewType())
    }
    return this
}

回答1:

I have a little bit different approach. You can create an extension for your ViewHolder

fun <T : RecyclerView.ViewHolder> T.listen(event: (position: Int, type: Int) -> Unit): T {
    itemView.setOnClickListener {
        event.invoke(getAdapterPosition(), getItemViewType())
    }
    return this
}

Then use it in adapter like this

class MyAdapter : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

    val items: MutableList<String> = arrayListOf()

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder? {
        val inflater = LayoutInflater.from(parent!!.getContext())
        val view = inflater.inflate(R.layout.item_view, parent, false)
        return MyViewHolder(view).listen { pos, type ->
            val item = items.get(pos)
            //TODO do other stuff here
        }
    }

    override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {

    }

    override fun getItemCount(): Int {
        return items.size()
    }


    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    }
}

I am working with my colleagues on library providing such extensions.



回答2:

My solution is like a combination of the previous ones with a super clean call from the activity.

ContactAdapter:

class ContactAdapter @Inject constructor() : RecyclerView.Adapter<ContactAdapter.ViewHolder>() {

    var onItemClick: ((Contact) -> Unit)? = null
    var contacts: List<Contact> = emptyList()

    ...

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val contact = contacts[position]

        holder.email.text = contact.email
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val email: TextView = itemView.email

        init {
            itemView.setOnClickListener {
                onItemClick?.invoke(contacts[adapterPosition])
            }
        }
    }
}

ContactActivity:

override fun setupRecyclerAdapter() {
    recyclerView.adapter = contactAdapter
    recyclerView.layoutManager = LinearLayoutManager(this)

    contactAdapter.onItemClick = { contact ->

        // do something with your item
        Log.d("TAG", contact.email)
    }
}


回答3:

In case anyone is looking for a more no-frills answer, I tried the following - which is very similar to the solution from AfzalivE:

In my Adapter class I passed the clickListener as a parameter. On onBindViewHolder, I've used setOnClickListener to call clickListener and handle click event.

MyAdapter.kt:

class MyAdapter constructor(objects: ArrayList<MyObject>, val clickListener: (MyObject) -> Unit) : RecyclerView.Adapter<MyAdapter.Holder>() {

    private var mObjects : ArrayList<MyObject> = ArrayList<MyObject>()

    init {
        mObjects = objects
    }

    override fun onBindViewHolder(holder: Holder?, position: Int) {
        var item : MyObject = objects[position]

        // Calling the clickListener sent by the constructor
        holder?.containerView?.setOnClickListener { clickListener(item) }
    }

    // More code (ViewHolder definitions and stuff)...

}

Note: I needed a reference from my list item's container (the root view), which in this case is containerView

Then I passed my object as parameter without need for searching it on a list again and handle it directly on my Activity class, in the moment I set the adapter:

MyActivity.kt:

myRecyclerView?.adapter = MyAdapter(mObjects) {
    Log.e("Activity", "Clicked on item ${it.itemName}")
}  

Update

If you need to get the position of the clicked item, just define it as parameter on the callback and then send it back later. Notice the val clickListener: (MyObject, Int) -> Unit below:

MyAdapter.kt

class MyAdapter constructor(objects: ArrayList<MyObject>, val clickListener: (MyObject, Int) -> Unit) : RecyclerView.Adapter<MyAdapter.Holder>() {
    // Rest of the code...

Then on onBindViewHolder() you pass the position when calling the callback method:

override fun onBindViewHolder(holder: Holder?, position: Int) {
    var item : MyObject = objects[position]

    // Calling the clickListener sent by the constructor
    holder?.containerView?.setOnClickListener { clickListener(item, position) }
}

And on MyActivity.kt, you'll have to change the way you set the adapter so you can get the position. Like this:

myRecyclerView?.adapter = MyAdapter(mObjects) { itemDto: MyObject, position: Int ->
        Log.e("MyActivity", "Clicked on item  ${itemDto.someItemPropertyLikeName} at position $position")
    }


回答4:

I think the most elegant solution is to give this responsibility to recyclerView and not to view or even adapt it.

for that we need:

1: Create RecyclerItemClickListener file

class RecyclerItemClickListener(private val mRecycler: RecyclerView, private val clickListener: OnClickListener? = null, private val longClickListener: OnLongClickListener? = null) : RecyclerView.OnChildAttachStateChangeListener {

    override fun onChildViewDetachedFromWindow(view: View?) {
        view?.setOnClickListener(null)
        view?.setOnLongClickListener(null)
    }

    override fun onChildViewAttachedToWindow(view: View?) {
        view?.setOnClickListener { v -> setOnChildAttachedToWindow(v) }
    }

    private fun setOnChildAttachedToWindow(v: View?) {
        if (v != null) {
            val position = mRecycler.getChildLayoutPosition(v)
            if (position >= 0) {
                clickListener?.onItemClick(position, v)
                longClickListener?.onLongItemClick(position, v)
            }
        }
    }

    interface OnClickListener {
        fun onItemClick(position: Int, view: View)
    }

    interface OnLongClickListener {
        fun onLongItemClick(position: Int, view: View)
    }
}

2: Create/Add extensions for RecyclerView:

import android.support.v7.widget.RecyclerView
import com.decathlon.manager.internal.common.RecyclerItemClickListener

fun RecyclerView.affectOnItemClick(listener: RecyclerItemClickListener.OnClickListener) {
    this.addOnChildAttachStateChangeListener(RecyclerItemClickListener(this, listener, null))
}

fun RecyclerView.affectOnLongItemClick(listener: RecyclerItemClickListener.OnLongClickListener) {
    this.addOnChildAttachStateChangeListener(RecyclerItemClickListener(this, null, listener))
}

fun RecyclerView.affectOnItemClicks(onClick: RecyclerItemClickListener.OnClickListener, onLongClick: RecyclerItemClickListener.OnLongClickListener) {
    this.addOnChildAttachStateChangeListener(RecyclerItemClickListener(this, onClick, onLongClick))
}

3: And finally the use (i suppose you use kotlinx)

import kotlinx.android.synthetic.main.{your_layout_name}.*
class FragmentName : Fragment() {
    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        recycler.affectOnItemClick(object : RecyclerItemClickListener.OnClickListener {
            override fun onItemClick(position: Int, view: View) {
                //todo
            }
        })
    }
}


回答5:

You could try something like:

public class MainActivity : ActionBarActivity() {
    protected override fun onCreate(savedInstanceState: Bundle?) {
        [...]
        val adapter = DrawAdapter(::onItemClick)
        [...]
    }
}

fun onItemClick(view: View, position: Int) {
    //Do work
}

and SAM convertion just works like in Java 8, so just use a lambda:

public class MainActivity : ActionBarActivity() {
    protected override fun onCreate(savedInstanceState: Bundle?) {
        [...]
        val adapter = DrawAdapter({view, position -> /*Do work*/ })
        [...]
    }
}


回答6:

Adapter constructor declaration

class YourAdapter(private val mListener: (ItemObject) -> Unit) : RecyclerView.Adapter<ViewHolder>()

Adapter::onBindViewHolder

holder.itemView.setOnClickListener {
    mListener.invoke(item) // <- item instance of ItemObject
}

How to Use

mTypesWasteAdapter = YourAdapter({ it.something()})

Basically, you will receive the ItemObject as it in the lambda argument.



回答7:

In RecyclerView you can put click on inflated view inside ViewHolder class and call it from onBindViewHolder callback method for example:

class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    val view = view
    val tv_message = view.tv_message
    val tv_address = view.tv_address

    fun bind(listViewItem: ListViewItem) {
        view.setOnClickListener(View.OnClickListener {

            Toast.makeText(
                view.context, 
                "Name: " + listViewItem.name + "/n Address: " + listViewItem.address, 
                Toast.LENGTH_LONG).show()
            })
        }
    }
}

You can call from adapter onBindViewHolder() method:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {

    val listViewItem: ListViewItem = mListViewItems[position]
    holder.tv_message.text = listViewItem.name
    holder.tv_address.text = listViewItem.address
    holder.bind(mListViewItems[position]);
}


回答8:

Sorry for the delay, Got an awesome answer from this link and it was in Java.. Did some Homework and converted it to Kotlin..

Now it is working Properly.. Here is the Code,

Create a class named RecyclerItemClickListenr,

class RecyclerItemClickListenr(context: Context, recyclerView: RecyclerView, private val mListener: OnItemClickListener?) : RecyclerView.OnItemTouchListener {

private val mGestureDetector: GestureDetector

interface OnItemClickListener {
    fun onItemClick(view: View, position: Int)

    fun onItemLongClick(view: View?, position: Int)
}

init {

    mGestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
        override fun onSingleTapUp(e: MotionEvent): Boolean {
            return true
        }

        override fun onLongPress(e: MotionEvent) {
            val childView = recyclerView.findChildViewUnder(e.x, e.y)

            if (childView != null && mListener != null) {
                mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView))
            }
        }
    })
}

override fun onInterceptTouchEvent(view: RecyclerView, e: MotionEvent): Boolean {
    val childView = view.findChildViewUnder(e.x, e.y)

    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildAdapterPosition(childView))
    }

    return false
}

override fun onTouchEvent(view: RecyclerView, motionEvent: MotionEvent) {}

override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}}

and access it from Activity/Fragment as

recyclerView.addOnItemTouchListener(RecyclerItemClickListenr(this, recyclerView, object : RecyclerItemClickListenr.OnItemClickListener {

        override fun onItemClick(view: View, position: Int) {
            //do your work here..
        }
        override fun onItemLongClick(view: View?, position: Int) {
            TODO("do nothing")
        }
    }))


回答9:

Two ways you can have an access to recyclerview in kotlin is first you can directly declare OnClickListener in adapter and make redirection inside it and second way is you can redirect your onclick to fragment/activity where you have set adapter of recycler

1.

 class CartAdapter(context: Context) : RecyclerView.Adapter<CartAdapter.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.layout_cart, parent, false));
        }

        override fun getItemCount(): Int {
            return 10;
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
           holder.itemView.rtbProductRating.setOnClickListener{

            var iNavigation= Intent(context,MainActivity::class.java)
            iNavigation.flags= Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT
            context.startActivity(iNavigation)

// directly redirect your activity from adapter
           }

        }

        class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)
    } 

Second way you can have is redirect your adapter click to fragment/activity and then redirect your activity from there instead of redirecting from adapter

 class CartAdapter(context: Context, onClickListener: View.OnClickListener) : RecyclerView.Adapter<CartAdapter.ViewHolder>() {
        var context = context
        var onClickListener = onClickListener
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.layout_cart, parent, false));
        }

        override fun getItemCount(): Int {
            return 10;
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {

//set your position to the view
            holder.itemView.rtbProductRating.tag = position

//redirect click to the fragment
            holder.itemView.rtbProductRating.setOnClickListener {
                onClickListener.onClick(holder.itemView.rtbProductRating)

            }
    //        holder.itemView.tv_waybill_count.text = holder.itemView.context.getString(R.string.waybills,5)
        }

        class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)
    }


Your fragment will look like:

class CartFragment: BaseFragment(),View.OnClickListener {
    override val layout= R.layout.frg_cart

     override fun onClick(v: View?) {
      var position=v?.tag as Int

        if(position==0){
            var iNavigation= Intent(this,MainActivity::class.java)
            iNavigation.flag=Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT
            startActivity(iNavigation)
        }
    }

  override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        listener()
    }

    private fun listener() {
        cart_rv.adapter=CartAdapter(activity,this)
    }
}


回答10:

RecyclerItemClickListener

package com.mypackage.custom 
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View


@Suppress("DEPRECATION")
class RecyclerItemClickListener(context: Context, private val mListener: OnItemClickListener?) : RecyclerView.OnItemTouchListener {

    private var mGestureDetector: GestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
        override fun onSingleTapUp(e: MotionEvent): Boolean {
            return true
        }
    })

    interface OnItemClickListener {
        fun onItemClick(view: View, position: Int)
    }

    override fun onInterceptTouchEvent(view: RecyclerView, e: MotionEvent): Boolean {
        val childView = view.findChildViewUnder(e.x, e.y)
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildPosition(childView))
            return true
        }
        return false
    }

    override fun onTouchEvent(view: RecyclerView, motionEvent: MotionEvent) {}

    override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
}

For Activity:

 recyclerView!!.addOnItemTouchListener(
                RecyclerItemClickListener(this!!, object : RecyclerItemClickListener.OnItemClickListener {
                    override fun onItemClick(view: View, position: Int) {
                        //Write your code here
                    }
                })

For Fragment:

recyclerView!!.addOnItemTouchListener(
                RecyclerItemClickListener(this!!.activity!!, object : RecyclerItemClickListener.OnItemClickListener {
                    override fun onItemClick(view: View, position: Int) {
                        //Write your code here
                    }
                })


回答11:

OH what the heck someone might like this We all place edit and trashcan images in out recyclerview and would like something to happen when they are clicked. Here is our Kotlin example

This is in a card view that is inflated in the Adapter

    <RelativeLayout
    android:id="@+id/editCLICK"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_marginStart="370dp"
    android:paddingLeft="6dp"
    android:paddingRight="6dp"
    android:paddingTop="12dp">

    <ImageView
        android:id="@+id/ivEdit"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="@color/color_Transparent"
        android:src="@drawable/ic_edit"
        android:tint="@color/color_lightBlue" />

</RelativeLayout>

then in the Adapter we do some binding

    override fun onBindViewHolder(holder: ParentViewHolder, position: Int) {
    val items = parentList[position]
    holder.item.text = items.dept


    holder.editCLICK.setOnClickListener {
        val i = Intent(context, EnterParentActivity::class.java)
        i.putExtra("FROM", "U")
        i.putExtra("MainActId",items.idD)
        i.putExtra("PFK",items.fkD)
        i.putExtra("ET",items.dept)
        i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        context.startActivity(i)
    }
}


inner class ParentViewHolder(view: View):RecyclerView.ViewHolder(view){
    var item: TextView = view.findViewById(R.id.tvDept) as TextView
    var editCLICK: RelativeLayout = view.findViewById(R.id.editCLICK) as RelativeLayout
}

Simple quick and reliable enjoy



回答12:

You don't need to write extension function to ViewHolder or something like this.
Best practice; use Higher-Order Function

MainRecyclerAdapter

class MainRecyclerAdapter(val news: JSONArray, private val itemClickListener: (Int) -> Unit) : RecyclerView.Adapter<MainRecyclerAdapter.ViewHolder>() {}

Just add a Higher-order func. like itemClickListener and then go to the ViewHolder class. Write this function to your bind function as parameter and set this to itemView Like that :

MainRecyclerAdapter.ViewHolder

 class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {

        fun bind(newsItem: JSONObject,itemClickListener:(Int)->Unit) {
            //Some Stuff here..

            itemView.setOnClickListener { itemClickListener(adapterPosition) }

        }
    }

Use this method onBindViewHolder

OnBindViewHolder

 override fun onBindViewHolder(holder: MainRecyclerAdapter.ViewHolder, position: Int) {

        holder.bind(news.getJSONObject(position),itemClickListener)
    }

And now you can write your onClick function in any activity or fragments.. Just give as parameter.

Activity or Fragment

val itemOnClick: (Int) -> Unit = { position ->
                newsRecyclerView.adapter!!.notifyDataSetChanged()
                Toast.makeText(this.context,"$position. item clicked.",Toast.LENGTH_SHORT).show()
            }
 newsRecyclerView.adapter = MainRecyclerAdapter(news,itemClickListener = itemOnClick)


回答13:

Here is my MainActivity.kt class that uses recyclerview to populate location data. It has a simple on item click listener interface that you can implement.

    class MainActivity : AppCompatActivity() {

        private lateinit var recyclerView: RecyclerView
        private lateinit var viewAdapter: RecyclerView.Adapter<*>
        private lateinit var viewManager: RecyclerView.LayoutManager
        private var locationArrayList = arrayListOf<Location>()

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)

            //create locations
            var ny = Location("New York")
            var la = Location("Los Angeles")
            locationArrayList.addAll(listOf(ny, la))

            viewManager = LinearLayoutManager(this)
            viewAdapter = LocationsAdapter(locationArrayList)

            recyclerView = findViewById<RecyclerView>(R.id.recyclerView).apply {
                // use this setting to improve performance if you know that changes
                // in content do not change the layout size of the RecyclerView
                setHasFixedSize(true)

                // use a linear layout manager
                layoutManager = viewManager

                // specify an viewAdapter 
                adapter = viewAdapter

            }

    //recycler view click listener implement
            recyclerView.addOnItemClickListener(object: OnItemClickListener {
                override fun onItemClicked(position: Int, view: View) {
                    // Your logic
                    Toast.makeText(this@MainActivity, locationArrayList[position].locationName, Toast.LENGTH_SHORT).show()
                }
            })

        }

    //on item click interface
        interface OnItemClickListener {
            fun onItemClicked(position: Int, view: View)
        }

        fun RecyclerView.addOnItemClickListener(onClickListener: OnItemClickListener) {
            this.addOnChildAttachStateChangeListener(object: RecyclerView.OnChildAttachStateChangeListener {
                override fun onChildViewDetachedFromWindow(view: View?) {
                    view?.setOnClickListener(null)
                }

                override fun onChildViewAttachedToWindow(view: View?) {
                    view?.setOnClickListener({
                        val holder = getChildViewHolder(view)
                        onClickListener.onItemClicked(holder.adapterPosition, view)
                    })
                }
            })
        }
//end of interface
    }


回答14:

If someone interested in the old way implementation..

I posted full example which also reduces your adapter code as well. It uses the old pattern of getting callback..

Project level gradle

buildscript {
    ext.kotlin_version = '1.3.10'
    repositories {
        google()
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"//newly added

        classpath 'com.google.gms:google-services:4.1.0' // google-services plugin

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App level Gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'org.jetbrains.kotlin.android.extensions'//it is used for @Percelize

android {
    compileSdkVersion 28
    dataBinding {
        enabled = true
    }
    androidExtensions {
        experimental = true
    }
    defaultConfig {
        applicationId 'broadpeak.firebase.learning'
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

/*kapt {
    generateStubs = true
}*/
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-core:16.0.5'
    implementation 'com.google.firebase:firebase-firestore:17.1.3'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-messaging:17.3.4'
    implementation 'com.google.code.gson:gson:2.8.5'

    implementation 'com.firebaseui:firebase-ui-auth:4.1.0'

    implementation 'com.github.bumptech.glide:glide:4.8.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
    ////kapt "com.android.databinding:compiler:$android_plugin_version"\ // not required above 3.2.0
    ///kapt "com.android.databinding:compiler:3.1.4"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

SubjectListActivity.class

class SubjectListActivity : BaseActivity() {

    var subjects = mutableListOf<SubjectBO>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.question_list_activity)

        recycler_view.itemAnimator = DefaultItemAnimator()
        recycler_view.setHasFixedSize(true)
        recycler_view.layoutManager = LinearLayoutManager(this@SubjectListActivity)

        db.collection("tagCollection").get().addOnSuccessListener { querySnapshot ->
            if (querySnapshot.isEmpty()) {
                Log.d(TAG, "onSuccess: LIST EMPTY")
            } else {
                // Convert the whole Query Snapshot to a list
                // of objects directly! No need to fetch each document.
                subjects = querySnapshot.toObjects(SubjectBO::class.java)

                if(subjects.size > 0){
                    recycler_view.adapter = SubjectAdapter(subjects, object : OnRecyclerItemClickListener {
                        override fun onItemClicked(view: View?, position: Int) {
                            var intent = Intent(this@SubjectListActivity,McqActivity::class.java)
                            intent.putExtra("keyTagBO",subjects.get(position))
                            startActivity(intent)
                        }
                    });
                }

            }
        }.addOnFailureListener { exception ->
            exception.printStackTrace()
        }
    }

SubjectAdapter.class

class SubjectAdapter(items: List<SubjectBO>, onRecyclerItemClickListener: OnRecyclerItemClickListener)
    : BaseAdapter<SubjectBO, SubjectViewHolder>(items, onRecyclerItemClickListener) {

    override fun onCreateViewHolder(parent: ViewGroup, p1: Int): SubjectViewHolder {
        return SubjectViewHolder(parent, R.layout.item_subject, onRecyclerItemClickListener)
    }
}

SubjectViewHolder.class

class SubjectViewHolder(parent: ViewGroup, itemLayoutId: Int, onRecyclerItemClickListener:
    OnRecyclerItemClickListener) : BaseViewHolder<SubjectBO>(parent, itemLayoutId, onRecyclerItemClickListener) {

    override fun bindData(data: SubjectBO) {
        itemView.tvTitle.setText(data.tagName)
    }
}

BaseAdapter.class

abstract class BaseAdapter<T, U : BaseViewHolder<T>>
(var items: List<T>, var onRecyclerItemClickListener: OnRecyclerItemClickListener)
    : RecyclerView.Adapter<U>() {

    override fun getItemCount(): Int {
        return items.size
    }

    override fun onBindViewHolder(holder: U, pos: Int) {
        holder.bindData(items.get(pos))
    }
}

BaseViewHolder.class

abstract class BaseViewHolder<T : BaseModel>(parent: ViewGroup, @LayoutRes itemLayoutId: Int,
                                             var onRecyclerItemClickListener: OnRecyclerItemClickListener) :
        RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(itemLayoutId, parent,
                false)), View.OnClickListener {

    override fun onClick(v: View?) {
        onRecyclerItemClickListener.onItemClicked(v, adapterPosition)
    }

    abstract fun bindData(data: T)

    init {
        itemView.setOnClickListener(this)
    }
}

OnRecyclerItemClickListener.class

interface OnRecyclerItemClickListener{
    fun onItemClicked(view: View?, position: Int)
}


回答15:

Add ClickListener code on onBindViewHolder fun

override fun onBindViewHolder(holder: ViewHolder, position: Int) {

    holder.vieww.textView.setText(arr.get(position))

    holder.vieww.setOnClickListener {(holder.vieww.textView.setTextColor(Color.GREEN))} // click event
}