Home > Enterprise >  How to implement implicit intent to RecyclerView on Kotlin
How to implement implicit intent to RecyclerView on Kotlin

Time:10-11

I want to add onClick on my RecyclerView item images for navigating to Browser but it requires context how can I access the context

class MovieAdapter(val movies: List<Data>, val activity: Activity) : RecyclerView.Adapter<MovieAdapter.ViewHolder>(){
class ViewHolder(itemView: View):RecyclerView.ViewHolder(itemView) {
    val txtTitle = itemView.findViewById<TextView>(R.id.txtName)
    val txtYear = itemView.findViewById<TextView>(R.id.txtPrice)
    val image = itemView.findViewById<ImageView>(R.id.image)
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.item_movie,parent,false)
    return ViewHolder(view)
}

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

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val movie:Data=movies[position]
    holder.txtTitle.setText(movie.animeName)
    holder.txtYear.setText(movie.animeİd.toString())
    Glide.with(activity).load(movie.animeİmg).into(holder.image)
    holder.image.setOnClickListener {
        val intent = Intent(Intent.ACTION_VIEW,Uri.parse("https://www.google.com/search?q=" holder.txtTitle))
        startActivity(intent)
    }



}

}

CodePudding user response:

You already have context in form of activity. You can use that.

activity.startActivity(intent)

You can also get a Context from any View using view.context, for example holder.image.context

CodePudding user response:

Pass Context instead of Activity.

class MovieAdapter(val movies: List<Data>, val context: Context) RecyclerView.Adapter<MovieAdapter.ViewHolder>() {
{

So in my Fragment I could just call it like

MovieAdapter(requireActivity().baseContext)

I think passing Context is enough for Adapters.

CodePudding user response:

You can add a listener to your adapter. You can listen to this listener from your adapter. I will put a code snippet below to give you an idea.

MovieAdapter(val movies: List<Data>, val fooListener: (Sting) -> Unit)


//When you create the adapter instance(Activity)
MovieAdapter(list){ url ->
 val intent = Intent(Intent.ACTION_VIEW,Uri.parse(url))
 startActivity(intent)
}
  • Related