Kotlin: Fragment not attached, Unable to instantiate fragment calling fragment const caused 异常

Kotlin: Fragment not attached, Unable to instantiate fragment calling fragment const caused exception

我正在尝试将 childFragmentManager 从片段传递到适配器。当前片段是从另一个片段调用的,而不是 activity.

片段 class 有一个 val

class DisplaySchoolFrag : BaseFragment<binding, DisplaySchoolViewModel>{
...

private val adapter = DisplaySchoolAdapter(childFragmentManager)

在适配器中,我只有 childFrag 的 const 声明,暂时没有其他用途。

class DisplaySchoolAdapter(childFrag: FragmentManager) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

我需要适配器内部的 childFragmentManager,因为在适配器内部 class 有一个按钮可以指向 bottomsheet 片段。

FragmentHostCallback<?> mhost
getChildFrar(){
if (this.mHost == null) {
            throw new IllegalStateException("Fragment " + this + " has not been attached yet.");

此行导致片段未附加,无法实例化片段调用片段常量导致异常

我试过了

lateinit var childFrag : FragmentManager


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
         childFrag = childFragmentManager
        return super.onCreateView(inflater, container, savedInstanceState)
    }

将 childFrag 传递到 DisplaySchoolAdapter(childFrag) 声明中仍然出现错误。

您应该将回调传递给 DisplaySchoolAdapter 并覆盖单个项目的 setOnClickListener 侦听器并调用回调。

class DisplaySchoolAdapter(lambdaToBeInvoked: () -> Unit): RecyclerView.Adapter<SomeViewHolder>() {

   ... set up your adapter

   override fun onBindViewHolder(holder: SomeViewHolder, position: Int) {
     val item = items[position]
     holder.bind(item)
     holder.itemView.setOnClickListener { lambdaToBeInvoked() }
   }
}

您可以在适配器的其余部分填写实施细节,但 onBindViewHolder 是您调用回调的地方。如果您需要向其中传递任何参数,请随时在您的实现中添加这些参数。

然后在您的片段中,当您实例化您的适配器时,您将传递您希望您的 childFragment 执行的操作。

class YourFragment: FragmentActivity() {
 
    override onCreate() {
         
         val adapter = DisplaySchoolAdapter {
              // have your childFragment navigate to somewhere
         }

         recyclerView.adapter = adapter
         recyclerView.layoutManager = LinearLayoutManager()
    }

}