簡體   English   中英

如何通過單擊左側同一頁面上的回收視圖項目來更改或替換右側的布局 - android kotlin

[英]How can I change or replace layout on the right by clicking on a recycleview item on the left same page- android kotlin

我有一個布局,分為兩部分,左側的 RecyleView 和右側的詳細信息。 我希望當我單擊左側的項目時,右側的布局將根據單擊的項目進行替換。 有人可以幫助我實現這一目標,或者幫助我采取更好的方法。 謝謝

我想要的示例圖片

你可以試試這個簡單的解決方案,使用界面。

在您的適配器中創建一個接口,用於在您的項目中實現 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM