1

I want to access a variable in an adapter class called item so that I could use it in my main activity. So far I've tried adding open before the adapter class and using object and companion object. How can I fix this problem?

class GrammarAdapter(private val context: Context, private val items: ArrayList<String>) :
    RecyclerView.Adapter<GrammarAdapter.ViewHolder>() {

    class ViewHolder(binding: GrammarItemRowBinding) : RecyclerView.ViewHolder(binding.root) {
        val tvItem = binding.tvItemName
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            GrammarItemRowBinding.inflate(LayoutInflater.from(context), parent, false)
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]
        holder.tvItem.text = item



        holder.itemView.setOnClickListener {
            when (item) {
                "Countable and uncountable nouns" -> {
                    val intent = Intent(holder.itemView.context, CountableUncountable::class.java)
                    intent.putExtra("clickedGrammarTopic", item)
                    holder.itemView.context.startActivity(intent)
                }
                "Singular and plural nouns" -> {
                    val intent = Intent(holder.itemView.context, Singular and plural nouns::class.java)
                    intent.putExtra("clickedGrammarTopic", item)
                    holder.itemView.context.startActivity(intent)
                }
...
Aschente
  • 105
  • 7

2 Answers2

1

As long as items is not private you can do something like:

val item = (myRecycler.adapter as MyAdapterClass).items[position]

However thats not really the best practice and you may want to rethink how your managing your apps data perhaps you should look into ViewModels

Quinn
  • 7,072
  • 7
  • 39
  • 61
  • Sorry, I guess I used my .adapter as a view binder. Can I bother you to have a look at a couple more lines? I just edited the question. This is my first time coding with kotlin so I hope I didn't make your eyes bleed. – Aschente May 18 '21 at 19:06
0

You have to use the callback pattern via an interface

interface Callback {
    fun onClickedRow(item: String)
}

In the adapter constructor

class GrammarAdapter(... , private val callback: Callback) : ...

And modify the interaction

holder.itemView.setOnClickListener {
    callback.onClickedRow(item)
}

You have to implement the interface in the activity or fragment

clas MyFragment : Callback {

    override fun onClickedRow(item: String) {
         //do something here with your item
    }
}

And instantiate your adapter with the callback as an argument

val adapter = GrammarAdapter(..., this@MyFragment) //depending on your scope it can be simple this

Now when the user clicks the method override fun onClickedRow(... is going to be triggered on the activity or fragment

cutiko
  • 9,887
  • 3
  • 45
  • 59