I have a recyclerview and a correspoinding viewholder to hold individual item. The viewholder has button which onClick needs to communicate with backend. I have a repository class that talks with backend present as the part of my activity.
class QuestionDetailsActivity : AppCompatActivity() {
@Inject
lateinit var myRepository: MyRepository
// OnCreate other functionality etc.
}
Below is how my viewholder layout looks like.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/updateBackendButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Update"/>
<View
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Text view"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Right Button"/>
</LinearLayout>
my viewholder class as below
class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val button = view.updateBackendButton
init {
updateBackendButton.setOnClickListener {
// I would like to call backend here with textView data
}
}
companion object {
fun create(parent: ViewGroup): MyViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.my_item, parent, false)
return MyViewHolder(view)
}
}
}
How do I make the MyRepository available inside the viewHolder, shall I also inject that inside the viewholder or accept a method in my ViewHolder as an arugment from activity and invoke that method inside the viewholder with the argument?
I would create an interface to handle the onClick, and implement that interface on the Activity. There you have access to the Repo with your injecton.
updateBackendButton.setOnClickListener {
listener.onUpdateBackendButton()
}
The listener could be like follows:
interface YourListener {
fun onUpdateBackendButton()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.