我有一个 recyclerview 和一个对应的 viewholder 来保存单个项目。 viewholder 有按钮,onClick 需要与后端通信。 作为我 Activity 的一部分,我有一个与后端对话的存储库类。
class QuestionDetailsActivity : AppCompatActivity() {
@Inject
lateinit var myRepository: MyRepository
// OnCreate other functionality etc.
}
下面是我的 viewholder 布局的样子。
<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>
我的viewholder类如下
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)
}
}
}
我如何使 MyRepository 在 viewHolder 中可用,我是否也应该将它注入(inject)到 viewholder 中,或者在我的 ViewHolder 中接受一个方法作为来自 Activity 的参数,并在 viewholder 中调用该方法争论?
最佳答案
我会创建一个接口(interface)来处理 onClick,并在 Activity 上实现该接口(interface)。在那里,您可以使用您的注入(inject)器访问 Repo。
updateBackendButton.setOnClickListener {
listener.onUpdateBackendButton()
}
监听器可以是这样的:
interface YourListener {
fun onUpdateBackendButton()
}
关于android - 如何从 Recyclerview.ViewHolder 调用后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64595579/