class YourAdapter(val onclick: OnClickListener): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
interface OnClickListener {
fun onClickItem(position: Int)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
holder.itemView.setOnClickListener {
onclick.onClickItem(position) // Here i will pass position for Ex, you can pass anything you want depend on
// what's your declared in parameter of onClickItem function
}
}
在Activity中声明适配器并实现接口。
class YourActivity() : YourAdapter.OnClickListener() {
lateinit var adapter: YourAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
adapter = YourAdapter(this)
}
override fun onClickItem(position: Int) {
// now you can set content to the view on the right, i've pass position item of recyclerView over here.
// content will change based on item you click on the left.
// Ex, i have a TextView on the right.
myTextview.settext(position.toString())
}
}
2条答案
按热度按时间z9smfwbn1#
你可以尝试这个简单的解决方案,使用接口。
在适配器中创建一个接口,用于在项目中实现onClick。然后,在
onBindViewHolder
中调用它。例如:在Activity中声明适配器并实现接口。
6rvt4ljy2#
你的回答帮助了我。但是我在onBindViewHolder中所做的,我使用[position],如果position是say 1,那么我可以用新的片段替换片段: