FragmentPagerAdapter在子片段实例化之前触发getPageTitle()

时间:2019-02-04 12:23:11

标签: android kotlin android-viewpager android-tabs

给出一个选项卡式活动,以及每个选项卡的片段:

我要设置标签的标题。该标题基于托管的片段(属性)

private fun initializeViewPager(vp: ViewPager) {
    var frags = ArrayList<ArticleFragment>()
    for (art: Article in stocks) {
        frags.add(ArticleFragment.newInstance(art))
    }

    mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager, frags)
    vp.adapter = mSectionsPagerAdapter
    my_tabs.setupWithViewPager(vp)
}

我的适配器:

inner class SectionsPagerAdapter(fm: FragmentManager, 
mFragmentListParam: ArrayList<ArticleFragment>) :
    FragmentPagerAdapter(fm) {
    private var mFragmentList = mFragmentListParam

    override fun getItem(position: Int): ArticleFragment {
        return mFragmentList[position]
    }

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

    override fun getPageTitle(position: Int): CharSequence? {
        return mFragmentList[position].getTitle() // this does not work
        //return position.toString() // this works
    }
}

我的片段类定义:

class ArticleFragment : Fragment() {

var article : Article? = null

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    article = arguments?.getSerializable("KEY") as Article

    return inflater.inflate(R.layout.fragment_article, container, false)
}

public fun getTitle():String{
    return article.title // article is null when it is called from adapter
}

companion object {
    @JvmStatic
    fun newInstance(sat: Article) = ArticleFragment().apply {
        arguments = Bundle().apply {
            putSerializable("KEY", sat)
        }
    }
}

}

问题出在适配器上的override fun getPageTitle函数中,该函数试图在片段上调用getTitle()。但是,尽管已经创建了片段,但是来自片段的属性article仍然为空,因此它可以返回标题。

0 个答案:

没有答案