尝试将片段添加到适配器时找不到childFragmentManager

时间:2019-03-02 15:15:38

标签: android kotlin fragmentmanager androidx

我正在尝试使用适配器添加一些片段,但是似乎找不到childFragmentManager

  

未解决的参考:childFragmentManager

应该使用什么代替此错误?

class MyRVAdapter(private val myList: ArrayList<Item>) : RecyclerView.Adapter<MyRVAdapter.ViewHolder>() {
    override fun getItemCount(): Int {
        return myList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.myBtn.text = (myList[position].textBtnTitle)
     }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.my_cv, parent, false)

        return ViewHolder(v)
    }

    class ViewHolder (itemView : View):RecyclerView.ViewHolder(itemView) {
        val myBtn = itemView.findViewById<Button>(R.id.btn_a)!!

        init {
            myBtn.setOnClickListener {
                val builder = AlertDialog.Builder(myBtn.context)
                builder.setTitle(myList[position].txtDialogTitle)
                builder.setMessage(myList[position].txtDialogMessage)
                builder.setPositiveButton(android.R.string.ok){ dialog, _ -> dialog.dismiss() }

                val dialog: AlertDialog = builder.create()
                dialog.show()

                tabLayout = customView.findViewById(R.id.mTabLayout)
                viewPager = customView.findViewById(R.id.mViewPager)

                val adapter = TabbedDialogAdapter(childFragmentManager)
                adapter.addFragment("Tab A", TabbedDialogFragment.createInstance("Description A"))
                adapter.addFragment("Tab B", TabbedDialogFragment.createInstance("Description B"))
                adapter.addFragment("Tab C", TabbedDialogFragment.createInstance("Description C"))

                customView.mViewPager.adapter = adapter
                customView.mTabLayout.setupWithViewPager(customView.mViewPager)
            }
        }
    }
}

TabbedDialogAdapter

class TabbedDialogAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
    private var mFragmentCollection: MutableList<Fragment> = ArrayList()
    private var mTitleCollection: MutableList<String> = ArrayList()
    fun addFragment(title: String, fragment: Fragment) {
        mTitleCollection.add(title)
        mFragmentCollection.add(fragment)
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return mTitleCollection[position]
    }

    override fun getItem(position: Int): Fragment {
        return mFragmentCollection[position]
    }

    override fun getCount(): Int {
        return mFragmentCollection.size
    }
}

1 个答案:

答案 0 :(得分:0)

我认为viewHolder没有ChildFragmentManager的引用。 从片段/活动中获取childFragmentManager进入适配器

class MyRVAdapter(private val myList: ArrayList<Item>, fm: FragmentManager) : RecyclerView.Adapter<MyRVAdapter.ViewHolder>() 


return ViewHolder(v, fm)


val adapter = TabbedDialogAdapter(fm)