Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

android - (Kotlin) Setting a OnclickListener on a fragmentList Item

I′m making a tabbed activity, one of the fragments has to show a list of elements, in this case a cardview with a few things inside. I have tried to set a onClickListener on the cardview itself but it doesn′t seem to work (the clicking part, not the app itself),thank you for reading ,this is my onBind and inner class ViewHolder:

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val item = museus[position]
    holder.nom.text = item.nom
    holder.direccio.text = item.direccio
    holder.parentCardView.setOnClickListener { v: View? ->
        Toast.makeText(MyApp.instance, "Funciona", Toast.LENGTH_LONG)
    }¨


    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    val nom: TextView = view.findViewById(R.id.museu_nom)
    val direccio: TextView = view.findViewById(R.id.museu_direccio)
    val parentCardView: CardView= itemView.findViewById(R.id.parentCardView)
}

EDIT 1

I was able to set the onclickListener on the ViewHolder, Ichanged the contructor to have the activity context inside it.

class PreviewMuseoRecyclerViewAdapter(private val context: Context) : RecyclerView.Adapter() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    val nom: TextView = view.findViewById(R.id.museu_nom)
    val direccio: TextView = view.findViewById(R.id.museu_direccio)
    //val parentCardView: CardView= itemView.findViewById(R.id.parentCardView)
    init {
        view.setOnClickListener{
            Log.i("hola","Funciona2")
            context?.startActivity(Intent(context, Mood::class.java))
        }
    }
}

Now i just need to pass a value from the viewHolder onto the next activity, since you dont assing them in this inner class im a bit lost on how to do it.

context?.startActivity(Intent(context, Mood::class.java).putExtra("id", ?? ))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
holder.parentCardView.setOnClickListener{
Toast.makeText(context, "Funciona", Toast.LENGTH_LONG)
}

and you have to declare Context using the Primary constructor. Example below.

class FragmentAdapter(private val context: Context, private val fragmentList: MutableList?) : RecyclerView.Adapter() {
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...