Home > OS >  How can i connect an interface from adapter to activity?
How can i connect an interface from adapter to activity?

Time:11-24

I want to connect the interface from recyclerview adapter to my activity. How can I achieve this ?

This is my interface code

void onButtonClick(int position);

Here position is the position of the recyclerview adapter

Thanks

CodePudding user response:

Pass the listener to your adapter using its constructor. Like

// Code inside your activity
new MyAdapter(new MyListener()
     {
       void onButtonClick(){
           // implementation
        }
    });

CodePudding user response:

Language used : Android Kotlin

  1. first make interface and its abstract method
  2. implement interface to your activity class and override its method
  3. pass object of interface to adapter's constructor -> using interface object, you can call the method from activity

::-> interface implementation

interface OnAnswerClickListener { fun onAnswerClick(answer: String) }

::-> adapter implementation

class PlayerAnswersAdapter( private val answersList: List, private val onAnswerClickListener: OnAnswerClickListener ) : RecyclerView.Adapter<PlayerAnswersAdapter.AnswersViewHolder>() {

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

override fun onBindViewHolder(holder: AnswersViewHolder, position: Int) {
    holder.bind(answersList[position])
    holder.itemView.setOnClickListener {
        onAnswerClickListener.onAnswerClick(answersList[position])
    }
}

override fun getItemCount(): Int {
    return 9
}

class AnswersViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val textAnswer = itemView.findViewById<TextView>(R.id.textAnswer)

    fun bind(answer: String) {
        textAnswer.text = answer
    }
}

}

::-> activity

class QuestionAnswersActivity : AppCompatActivity(), OnAnswerClickListener {

override fun onAnswerClick(answer: String) { enter code here } }

  • Related