简体   繁体   中英

Call Activity method from RecyclerView Adapter using Kotlin

I want to call the

fun androidisgarbage(){

}

method which is in MainActivity from RecyclerView adapter so I try:

(getActivity() as MainActivity).androidisgarbage()

And get this error on getActivity:

None of the following functions can be called with the arguments supplied: 
public open fun getActivity(context: Context!, requestCode: Int, intent: Intent!, flags: Int): PendingIntent! defined in android.app.PendingIntent
public open fun getActivity(context: Context!, requestCode: Int, @RecentlyNonNull intent: Intent!, flags: Int, @RecentlyNullable options: Bundle!): PendingIntent! defined in android.app.PendingIntent

Using context which is passed from MainActivity like so:

(getActivity(context) as MainActivity).androidisgarbage()

also isn't working

Please help!

In activity

public interface OnClickListener {
    fun onClick()
}

val adapater = Adapter(items, object: OnClickListener {
    androidisgarbage()
})

In adapter,

class Adapater (val items: List<Any>, val listener: OnClickListener) : RV... {
...
    //call to fire event on Activity
    listener.onClick()
}

I think Use Context with Activity Name to call that method like i am using I sent context to adapter when calling that adapter from activity and then call it as

 (context as MainActivity).myMethod()   

worked for me

I know I am late to answer this question but it can help someone in future. You can call activity method in adapter by adapting following technique

class StudentListAdapter(context: Context,list: 
ArrayList<Student?>):RecyclerView.Adapter<StudentListAdapter.ViewHolder>() {
private var mContext = context
private var mList = list

// to call activity method do following 
// StudentList is activity
(mContext as StudentList).methodName()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM