【问题标题】:how to replace a fragment in kotlin from a onclicklistener inside a recyclerview如何从 recyclerview 中的 onclicklistener 替换 kotlin 中的片段
【发布时间】:2019-05-05 18:07:37
【问题描述】:

当我点击 recyclerView 中的项目时如何替换片段

我在适配器的onClickListener里面试过了

    childFragmentManager
                .beginTransaction()
                .replace(R.id.framefragment2, Fragment2())
                .commit()

没有成功它返回我

java.lang.IllegalArgumentException: No view found for id 0x7f0a0137 (com.test.justaapp:id/framefragment1) for fragment Fragmetnone{1ebd5fc #0 id=0x7f0a0137}

这是第一个片段的 mi xml 已经膨胀

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/framefragment1"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

和第二帧布局

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C0C0C0">

    <FrameLayout
        android:id="@+id/framefragment2"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

我一直在寻找几个小时,但无法让它工作,有什么想法吗?也许我在模仿一些非常简单的事情,任何帮助都会非常感谢。

【问题讨论】:

    标签: android-fragments kotlin android-recyclerview


    【解决方案1】:

    您可以在 ViewHolder 上实现一个接口,然后将该接口的实现从您的 Activity 传递给您的适配器。在您的适配器中,您在创建 CustomViewHolder 实例(创建方法)时传递实现。

    在您的活动/片段中:

    private val adapter = YourAdapter(object: CustomViewHolder.Listener {
        fun onClick() {
            // change the fragment here with the fragment manager of your activity/fragment.
        }
    })
    

    在您的适配器中:

    class YourAdapter(private val listener: CustomViewHolder.Listener): RecyclerView.Adapter {
    
        ...
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return CustomViewHolder(
                LayoutInflater.from(context).inflate(R.layout.view_layout, parent, false), 
                listener
            )
        }
    }
    

    ViewHolder 实现:

    class CustomViewHolder(view: View, private val listener: Listener): ViewHolder(view) {
    
        ...    
    
        interface Listener {
            fun onClick()
        }
    
        fun onCreate(parent: View, listener: Listener): CustomViewHolder {
            // inflate the view and return an instance of CustomViewHolder
        }
    
        fun onBind() {
            button.setOnClickListener {
                listener.onClick()
            }
        }    
    }
    

    我没有测试这段代码,但逻辑在这里。您只需要根据您的项目调整它即可。

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 2020-10-07
      • 2021-06-29
      • 2021-06-09
      相关资源
      最近更新 更多