[英]How can I change or replace layout on the right by clicking on a recycleview item on the left same page- android kotlin
你可以試試這個簡單的解決方案,使用界面。
在您的適配器中創建一個接口,用於在您的項目中實現 onClick。 然后,在onBindViewHolder
中調用它。 例如:
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())
}
}
你的回答幫助了我。 但是我在 onBindViewHolder 中所做的,我使用了 [位置],如果 position 是一個,那么我可以用新的片段替換片段:
holder.itemView.setOnClickListener {
if (position == 1) {
val activity = it.context as AppCompatActivity
val menFragment = MenFragment()
activity.supportFragmentManager.beginTransaction()
.replace(R.id.frameLayout, menFragment)
.commit()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.