Search code examples
androidandroid-studiokotlinandroid-activityandroid-adapter

How to call an Activity method in an Adapter


I'm working on a School Project and i have difficulites on it.

Basicly, I need to press a button and open a Google Map with a marker associated to coordinates.

To open a new MapActivity i use this in MainActivity:

fun launchGoogleActivity(latitude : Double, longitude : Double, title: String): Boolean 
{
   val intent = Intent(this, MapsActivity::class.java).apply 
   {
      putExtra("latitude", latitude)
      putExtra("longitude", longitude)
      putExtra("title", title)
   }
   startActivity(intent)
   return true
}

In my MapActivity I use this to put the new marker:

val extras = intent.extras
val latitude: Double
val longitude: Double
val title: String
latitude = extras?.getString("latitude")?.toDouble()!!
longitude = extras.getString("longitude")?.toDouble()!!
title = extras.getString("name").toString()

val newPoint = LatLng(latitude, longitude)
mMap.addMarker(MarkerOptions().position(newPoint).title(title))
mMap.moveCamera(CameraUpdateFactory.newLatLng(newPoint))

And I have these datas in my Adapter:

holder.buttonMap.setOnClickListener 
{
   val latitude = user?.location?.location?.latitude?.toDouble()
   val longitude = user?.location?.location?.longitude?.toDouble()
   val name : String = "Localisation de: " + user?.name?.nom + " " + user?.name?.prenom
}

How can i do launchGoogleActivity(latitude, longitude, name) in my Adapter ?

Thanks !


Solution

  • Pass function in your adapter

    class YourAdapter(private val listener : (Double, Double,String) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>()
    

    and in your viewHoler

    val latitude = user?.location?.location?.latitude?.toDouble()
    val longitude = user?.location?.location?.longitude?.toDouble()
    val name : String = "Localisation de: " + user?.name?.nom + " " + user?.name?.prenom
    
    
    holder.buttonMap.setOnClickListener {
       listener(latitude,longitude,name)
    }
    

    And in your MainActivity where you set the adapter

    YourAdapter(){latitude: Double, longitude: Double, name: String -> launchMapActivity(latitude,longitude,name)}